加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-13 16:35:33 所属栏目:百科 来源:网络整理
导读:我想将表table1的一列val1中的所有值复制到另一个表table2的一列val2。我在PostgreSQL中尝试过这个命令: update table2set val2 = (select val1 from table1) 但是我收到这个错误: ERROR: more than one row returned by a subquery used as an expression
我想将表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子句阻止不会改变任何东西的更新 – 这实际上总是一个好主意(全部成本,但没有收益 – 异常异常适用)。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读