更新Postgres中的列只会错误地返回一个值(Postgres 9.5.1)

时间:2017-04-10 22:05:20

标签: postgresql

假设我有一个由以下内容创建的表:

create table test.sales
(
 customer text,
 purchased text,
 date_purchased date,
 rownumber integer,
 primary key (customer, date_purchased)
)
;

insert into test.sales
values
('kevin', 'books', '2017-01-01'::date, null),
('kevin', 'movies', '2017-01-02'::date, null),
('paul', 'books', '2017-01-05'::date, null),
('paul', 'movies', '2017-01-07'::date, null)

此时,rownumber始终为NULL,我想将rownumber的值设为row_number() over (partition by customer order by date_purchased) as rownumber。我的方式如下:

update test.sales as a
set (rownumber) =
(
select
  row_number() over (partition by customer order by date_purchased) as rownumber
from test.sales as b
-- These fields correspond to the primary keys of the table.
where a.customer = b.customer
  and a.date_purchased = b.date_purchased
)

但出于某种原因,这又回来了:

customer    purchased   date_purchased  rownumber
kevin        books         1/1/17          1
kevin        movies        1/2/17          1
paul         books         1/5/17          1
paul         movies        1/7/17          1

我期待着这个:

customer    purchased   date_purchased  rownumber
kevin        books         1/1/17          1
kevin        movies        1/2/17          2
paul         books         1/5/17          1
paul         movies        1/7/17          2

请注意,在实际结果中,rownumber始终是1.为什么会这样?

1 个答案:

答案 0 :(得分:0)

你正在使用标量子查询。改为使用相关子查询:

UPDATE test.sales dst
SET rownumber = src.rownumber
FROM    ( SELECT customer,date_purchased
        , row_number() over (partition by customer order by date_purchased) as rownumber
        from test.sales 
        ) src
WHERE dst.customer = src.customer
  AND dst.date_purchased = src.date_purchased
        ;