Return 在 UPDATE 时更新了行属性

Return updated row attributes on UPDATE

我的查询如下:

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

如何 return 同一查询中 table 更新行的某些属性?

您可以使用 RETURNING 子句:

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

documentationUPDATE 语句的一部分。

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.

但通常使用连接而不是相关子查询更聪明:

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。通常,在这种情况下,您宁愿 更新行,这是我建议的查询所做的。

顺便说一句,SET 子句中的目标列不能是 table 限定的(无论如何只有 one table 被更新)。手册再次:

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.