gpt4 book ai didi

sql - Postgres : correlated subquery with NOT EXISTS

转载 作者:行者123 更新时间:2023-11-29 12:31:16 25 4
gpt4 key购买 nike

在 Oracle SQL 中,您可以轻松地根据相关子查询中的 NOT EXISTS 条件进行更新。这对于根据另一个查询或 ID 列表进行更新很有用。

子查询机制在 Postgres 中是不同的...我怎样才能达到相同的目标? http://sqlfiddle.com/#!1/1dbb8/55

在 Oracle 上你会怎么做

UPDATE UserInfo a
SET a.username = 'not found'
WHERE NOT EXISTS (SELECT 'X'
FROM UserOrder b
WHERE b.userid = a.userid)
AND a.userid in (1,2,3);

Postgres NOT EXISTS 查询:有效

SELECT u.userid, u.username
FROM UserInfo AS u
WHERE NOT EXISTS
( SELECT *
FROM UserOrder AS o
WHERE o.userid = u.userid
);

Postgres NOT EXISTS 更新:不起作用

UPDATE UserInfo
SET username = 'not found'
FROM (SELECT u.userid
FROM UserInfo AS u
WHERE NOT EXISTS
( SELECT *
FROM UserOrder AS o
WHERE o.userid = u.userid
)) em
WHERE em.userid = UserInfo.userid;

最佳答案

显然,每次您“运行脚本”时,Sqlfiddle 都会重新生成数据库内容。在与更新相同的脚本中运行选择。

您从 sqlfiddle 进行的 Oracle 查询几乎可以正常工作,但您忘记为 userid 参数设置别名。正确查询:

/* How you would do it on Oracle */
UPDATE UserInfo
SET username = 'not found'
WHERE NOT EXISTS (SELECT 'X'
FROM UserOrder b
WHERE b.userid = userinfo.userid);

关于sql - Postgres : correlated subquery with NOT EXISTS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23594135/

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