这可能是一个愚蠢的问题,但我正在努力与postgres更新。我有下表:
id | tableX_id| position |
---+----------+---------+
1 | 10 | |
2 | 10 | |
3 | 10 | |
4 | 10 | |
5 | 10 | |
6 | 11 | |
7 | 11 | |
8 | 12 | |
我需要像这样更新位置:
id | tableX_id| position |
---+----------+---------+
1 | 10 | 1 |
2 | 10 | 2 |
3 | 10 | 3 |
4 | 10 | 4 |
5 | 10 | 5 |
6 | 11 | 1 |
7 | 11 | 2 |
8 | 12 | 1 |
我有以下更新无效(将所有位置更新为1):
UPDATE tableY y
SET position = subquery.pos
FROM (
SELECT ROW_NUMBER() OVER() as pos
FROM tableY y2
JOIN tableX x on x.id = y2.tableX_id
) as subquery
答案 0 :(得分:1)
添加where subquery.id = tableY.id
,如下所示:
t=# update x set position = pos
from (select *,ROW_NUMBER() OVER(partition by x order by id) as pos FROM x) sub
where x.id = sub.id;
UPDATE 8
Time: 10.015 ms
t=# select * from x;
id | x | position
----+----+----------
1 | 10 | 1
2 | 10 | 2
3 | 10 | 3
4 | 10 | 4
5 | 10 | 5
6 | 11 | 1
7 | 11 | 2
8 | 12 | 1
(8 rows)