带有连接和顺序的Postgres RETURNING子句

时间:2016-12-29 21:43:18

标签: sql postgresql join sql-update sql-order-by

我有这个查询更新了一些行并返回RETURNING子句中的更新行。但是,即使我在内部查询中指定了ORDER BY mycolumnRETURNING返回的行也不会被排序。

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。)

1 个答案:

答案 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