根据之前postgres行

时间:2017-01-17 21:55:24

标签: postgresql

我正在运行postgres 9.4

我实际上是将现有的无组织结构更新为基于文件夹的组织。我自动为每个项目分配订单号以供用户重新排序,但是使用1次使用更新语句对所有这些值进行初始设置。但是,似乎SET正在从子句中获取子查询,而不是为它设置的每个连续行重新创建它。

这是我的查询示例:

UPDATE folder_items
SET order_number = 
(SELECT COALESCE(MAX(folder_items_2.order_number), 0) + 1
FROM folder_items AS folder_items_2
WHERE folder_items.parent_folder_id = folder_items_2.parent_folder_id
AND folder_items.folder_set_id = folder_items_2.folder_set_id
AND folder_items.id != folder_items_2.id);

用我的初始表:

         | folder_id    | folder_set_id | order_number
row 1    | 1            | 1             | null
row 2    | 2            | 1             | null
row 3    | 3            | 2             | null
row 4    | 4            | 2             | null
row 5    | 5            | 2             | null
row 6    | 6            | 3             | null

当我运行查询时,我得到类似

的内容
         | folder_id    | folder_set_id | order_number
row 1    | 1            | 1             | 1
row 2    | 2            | 1             | 1
row 3    | 3            | 2             | 1
row 4    | 4            | 2             | 1
row 5    | 5            | 2             | 1
row 6    | 6            | 3             | 1

但是,我想要的结果如下:

         | folder_id    | folder_set_id | order_number
row 1    | 1            | 1             | 1
row 2    | 2            | 1             | 2
row 3    | 3            | 2             | 1
row 4    | 4            | 2             | 2
row 5    | 5            | 2             | 3
row 6    | 6            | 3             | 1

有没有办法获得这些理想的结果?是一种最好的方法来做某种窗口函数,计算每行下面同一个folder_set_id中有多少个?

1 个答案:

答案 0 :(得分:1)

使用ROW_NUMBER计算ORDER_ID,然后更新表格。

with new_order as (
      SELECT "folder_id", 
              row_number() over ( partition by "folder_set_id"
                                  order by "folder_id") as rn
      FROM Table1
)
UPDATE Table1 AS t
SET "order_number" = n.rn
FROM new_order AS n
WHERE t."folder_id" = n."folder_id";

<强> SQL DEMO

<强>输出

| row_id | folder_id | folder_set_id | order_number |
|--------|-----------|---------------|--------------|
|  row 1 |         1 |             1 |            1 |
|  row 2 |         2 |             1 |            2 |
|  row 3 |         3 |             2 |            1 |
|  row 4 |         4 |             2 |            2 |
|  row 5 |         5 |             2 |            3 |
|  row 6 |         6 |             3 |            1 |