gpt4 book ai didi

sql - Postgres 错误 : More than one row returned by a subquery used as an expression

转载 作者:太空狗 更新时间:2023-10-30 01:39:10 45 4
gpt4 key购买 nike

我有两个独立的数据库。我正在尝试将一个数据库中的列更新为另一个数据库中列的值:

UPDATE customer
SET customer_id=
(SELECT t1 FROM dblink('port=5432, dbname=SERVER1 user=postgres password=309245',
'SELECT store_key FROM store') AS (t1 integer));

这是我收到的错误:

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

有什么想法吗?

最佳答案

技术上,要消除错误,请将 LIMIT 1 添加到子查询以最多返回 1 行.该声明仍然是无稽之谈。

... 'SELECT store_key FROM store LIMIT 1' ...

Practically, you want to match rows somehow instead of picking an arbitrary row from the remote table store to update every row of your local table customer.
I assume a text column match_name in both tables (UNIQUE in store) for the sake of this example:

... 'SELECT store_key FROM store     WHERE match_name = ' || quote_literal(customer.match_name)  ...

But that's an extremely expensive way of doing things.

Ideally, you completely rewrite the statement.

UPDATE customer c
SET customer_id = s.store_key
FROM dblink('port=5432, dbname=SERVER1 user=postgres password=309245'
, 'SELECT match_name, store_key FROM store')
AS s(match_name text, store_key integer)
WHERE c.match_name = s.match_name
AND c.customer_id IS DISTINCT FROM s.store_key;

这解决了您原始陈述中的一些问题。

显然,基本错误已修复。

通常最好在 FROM clause of an UPDATE statement 中加入额外的关系而不是为每一行运行相关子查询

当使用 dblink 时,以上内容变得重要一千倍。您不想为每一行调用 dblink(),那非常昂贵。调用一次以检索您需要的所有行。

对于相关子查询,如果在子查询中找不到行,该列将更新为 NULL,这几乎总是不是您想要的。在我更新的查询中,该行仅在找到匹配行时才会更新。否则,该行未被触及。

通常,当实际没有任何变化时,您不会希望更新行。那是什么都不做的代价高昂的(但仍然会产生死行)。 WHERE 子句中的最后一个表达式可防止此类空更新:

     AND   c.customer_id IS DISTINCT FROM sub.store_key

相关:

关于sql - Postgres 错误 : More than one row returned by a subquery used as an expression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21048955/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com