it might be a silly question but I am struggling with postgres update. I have following table:
id | tableX_id| position |
---+----------+---------+
1 | 10 | |
2 | 10 | |
3 | 10 | |
4 | 10 | |
5 | 10 | |
6 | 11 | |
7 | 11 | |
8 | 12 | |
I need to update position like this:
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 |
I have following update that doesnt work(update all position to 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
add where subquery.id = tableY.id
, as below:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.