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

标签 sql database postgresql subquery dblink

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

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/

相关文章:

sql - 从 regexp_matches 结果中获取第二个匹配项

mysql - 使用 mysql_fdw 或将表从 Postgres 连接到 MySQL

database - 如何通过在 postgres 的 pg_hba.conf 文件中指定 docker-compose 主机名来允许连接?

sql - 在日期差异上获得相同 FK 的前一项记录

sql - 在 Apache Pig 中计算连接表中的总和

mysql - 从具有相同 id 的多个表中检索数据

php - Magento 不获取新的数据库详细信息

php - SQL - 验证现有数据

c# - 使用 MARS 的缺点(多个事件结果集)

database - Cloud Firestore 是否支持 React Native