在 UPDATE 上返回更新的行属性

编程入门 行业动态 更新时间:2024-10-28 06:22:42
本文介绍了在 UPDATE 上返回更新的行属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的查询如下:

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?

推荐答案

使用 RETURNING 子句.

可选的 RETURNING 子句导致 UPDATE 计算并返回基于实际更新的每一行的值.任何表达式使用表的列,和/或 FROM 中提到的其他表的列,可以被计算.使用表列的新(更新后)值.

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

对于您的原始查询,如果子查询在 t2 中找不到任何行,则无论如何都会更新 t1 并将 t1.col 设置为 NULL.通常,在这种情况下,您宁愿不更新行,而我建议的查询正是这样做的.

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.

顺便说一句,SET 子句中的目标列不能是表限定的(无论如何只更新 一个 表).再次使用手册:

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

请勿在目标规范中包含表名列 — 例如,UPDATE table_name SET table_name.col = 1 无效.

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.

更多推荐

在 UPDATE 上返回更新的行属性

本文发布于:2023-10-23 03:34:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519636.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   UPDATE

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!