Return updated row attributes on UPDATE

时光毁灭记忆、已成空白 提交于 2020-12-29 05:31:05

问题


My query is as follow:

UPDATE t1 SET t1.foreign_key = (SELECT id FROM t2 WHERE t2.col = %s ) 
WHERE t1.col = %s

How do I return some attributes of the updated row in the table in the same query?


回答1:


Use the RETURNING clause.

The optional RETURNING clause causes UPDATE to compute and return value(s) based on each row actually updated. Any expression using the table's columns, and/or columns of other tables mentioned in FROM, can be computed. The new (post-update) values of the table's columns are used.

But typically it's smarter to use a join instead of a correlated subquery:

UPDATE t1
SET    foreign_key = t2.id
FROM   t2
WHERE  t2.col = %s
AND    t1.col = %s
RETURNING t1.*;   -- or only selected columns

With your original query, if the subquery finds no row in t2, t1 is updated anyway and t1.col is set to NULL. Typically, you'd rather not update the row in this case, which is what my suggested query does instead.

BTW, target columns in the SET clause cannot be table-qualified (only one table is updated anyway). The manual once more:

Do not include the table's name in the specification of a target column — for example, UPDATE table_name SET table_name.col = 1 is invalid.




回答2:


You can use the RETURNING clause:

UPDATE t1
    SET t1.foreign_key = (SELECT id FROM t2 WHERE t2.col = %s ) 
    WHERE t1.col = %s
    RETURNING *;

The documentation is part of the UPDATE statement.



来源:https://stackoverflow.com/questions/38948800/return-updated-row-attributes-on-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!