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

Postgresql 更新Postgres中的列只返回一个错误值(Postgres 9.5.1),postgresql,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', '

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

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)
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
)
此时,
rownumber
始终为
NULL
,我想将
rownumber
的值设置为rownumber(
row\u number())(按客户订单按购买日期划分)。我的做法如下:

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)
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。这是为什么?

您使用的是标量子查询。请改用相关子查询:



您正在使用标量子查询。请改用相关子查询:



有趣!我是否应该担心效率/可扩展性?我的理解是,相关子查询不能很好地处理大量行。请测试它。(至少结果是正确的,所以测试还是没用的…)有趣!我是否应该担心效率/可扩展性?我的理解是,相关子查询不能很好地处理大量行。请测试它。(至少结果是正确的,所以测试还是没用的…)