使用PostgreSQL中的另一个表的列更新表的列

前端之家收集整理的这篇文章主要介绍了使用PostgreSQL中的另一个表的列更新表的列前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想将表table1的一列val1中的所有值复制到另一个表table2的一列val2。我在Postgresql中尝试过这个命令:
update table2
set val2 = (select val1 from table1)

但是我收到这个错误

ERROR: more than one row returned by a subquery used as an expression

有办法吗?

您的 UPDATE查询应该是这样的:
UPDATE table2 t2
SET    val2 = t1.val1
FROM   table1 t1
WHERE  t2.table2_id = t1.table2_id
AND    t2.val2 IS DISTINCT FROM t1.val1  -- optional,to avoid empty updates

你拥有的方式,两个表的各行之间没有链接。 table2中的每行都会从table1中提取每一行。这没有任何意义(以昂贵的方式),并且也触发语法错误,因为此地方的子查询表达式仅允许返回单个值。

>我通过加入table2_id上的两个表来修复这个问题。用任何实际链接的两个替换。
>我重写UPDATE以加入table1(使用FROM子句),而不是运行相关的子查询,因为它通常会更快一个数量级。
它也可以防止在table1中找不到匹配的行时,table2.val2将被取消。相反,这种形式的查询对这些行没有任何影响。
>您可以在FROM列表中包含所有相同的内容,这些列表可以包含在纯SELECT(如多个表或子查询)中。 Per documentation:

from_list

A list of table expressions,allowing columns from other tables to
appear in the WHERE condition and the update expressions. This is
similar to the list of tables that can be specified in the 07002
of a SELECT statement. Note that the target table must not appear in
the from_list,unless you intend a self-join (in which case it must
appear with an alias in the from_list).

>最后的WHERE子句阻止不会改变任何东西的更新 – 这实际上总是一个好主意(全部成本,但没有收益 – 异常异常适用)。

原文链接:https://www.f2er.com/postgresql/192882.html

猜你在找的Postgre SQL相关文章