防止postgres内联更新子查询

时间:2016-06-02 15:09:17

标签: sql postgresql volatile sql-execution-plan

我有一张桌子

CREATE TABLE author (
    id SERIAL PRIMARY KEY,
    followers INTEGER[]
);
INSERT INTO author (followers)
       SELECT '{}'::INTEGER[]
       FROM generate_series(0, 1000);

我用ids填充它,并想添加随机粉丝。运行时出现问题

UPDATE author
SET followers = (SELECT array_agg(id)
                 FROM author
                 WHERE random() < 0.01);

Postgres试图变得聪明并只执行SELECT一次,导致相同的值一遍又一遍地重复。实现这一目标的正确方法是什么?我尝试使用OFFSET 0UDPATE .. FROM ..,但无济于事

1 个答案:

答案 0 :(得分:2)

我认为你需要在子查询和外部查询之间创建一个人工依赖。简单的事情:

UPDATE Author AS A1
SET
    followers = (
             SELECT array_agg(id)
             FROM Author
             WHERE
                 A1.author_id = A1.author_id AND
                 random() < 0.01);

(我猜到列名为author_id,但任何列都应该有效)