我有这个查询更新了一些行并返回RETURNING
子句中的更新行。但是,即使我在内部查询中指定了ORDER BY mycolumn
,RETURNING
返回的行也不会被排序。
UPDATE mytable SET status = 'A'
FROM
(
SELECT id FROM mytable
WHERE status = 'B'
ORDER BY mycolumn
LIMIT 100
FOR UPDATE
) sub
JOIN jointable j ON j.id = sub.id
WHERE mytable.id = sub.id
RETURNING *
我尝试在外部查询中添加ORDER BY
,例如在JOIN
之后或WHERE
之后,但在这两种情况下都出错了。如何让它按所需顺序返回行?
(在Update Returning Order by in postgresql中回答了类似的问题,但这并不包括JOIN,只包括ORDER。)
答案 0 :(得分:3)
使用CTE:
WITH updated as(
UPDATE mytable SET status = 'A'
FROM
(
SELECT id FROM mytable
WHERE status = 'B'
ORDER BY mycolumn
LIMIT 100
FOR UPDATE
) sub
JOIN jointable j ON j.id = sub.id
WHERE mytable.id = sub.id
RETURNING *
)
select *
from updated
ORDER BY mycolumn