0

我有几千条带有重复排序顺序的记录(这会导致其他查询中的重复条目),所以我试图为所有这些记录设置正确的排序顺序。

首先,我将它们全部设置为 -1,以便排序顺序从 0 开始,然后执行以下查询:

UPDATE op.customeraddress SET sortorder = (SELECT MAX(ca.sortorder) + 1 
                                           FROM op.customeraddress AS ca 
                                           WHERE ca.customerid = customeraddress.customerid) 
WHERE id IN (<subquery for IDs>)

问题是子查询中的 MAX() 似乎总是返回相同的值——它不知道更早的更新。

如果我手动逐条应用它,查询工作正常。

关于如何做到这一点而不必诉诸循环的任何想法?

4

2 回答 2

2

这应该这样做:

with new_order as 
(
   select ctid as rid,
          row_number() over (partition by customerid order by sortorder) as rn
   from customeraddress
) 
update customeraddress ca
  set sortorder = new_order.rn 
where ca.ctid = new_order.rid;
  and ca.id IN (<subquery for IDs>);

运行此之前无需重置排序顺序,它将根据旧顺序为一个客户ID重新编号所有客户地址。

上述解决方案需要 PostgreSQL 9.1(可写 CTE)

对于以前的版本,这应该这样做:

update customeraddress ca
   set ca.sortorder = t.sortorder
from 
(
   select ctid as rid,
          row_number() over (partition by customerid order by sortorder) as rn
   from customeraddress
)  t
where ca.ctid = t.rid
  and ca.id IN (<subquery for IDs>);
于 2012-06-14T22:04:12.967 回答
0

你可以使用一个序列:

CREATE TEMPORARY SEQUENCE sort_seq;
UPDATE op.customeraddress SET sort_order = (
     SELECT nextval('sort_seq')
     FROM op.customeraddress AS ca 
     WHERE ca.customerid = customeraddress.customerid
) WHERE id IN ...
于 2012-06-14T00:01:59.537 回答