简体   繁体   中英

Postgres RETURNING clause with join and order

I've got this query that updates some rows and returns the updated rows in the RETURNING clause. However, even though I've specified ORDER BY mycolumn in the inner query, the rows returned by RETURNING aren't ordered.

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 *

I tried putting an ORDER BY in the outer query, like after the JOIN or after the WHERE , but I get an error in both cases. How can I make it return the rows in the desired order?

(A similar question was answered in Update Returning Order by in postgresql but that doesn't include JOINs, only ORDER.)

Use 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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM