运动问题:
使用NOT EXISTS子句检查dogs表中不在users表中的所有用户。
我可以使用以下内部联接获得正确答案:
select d.user_guid as UserID, d.dog_guid as DogID
from dogs d
left join users u
on d.user_guid = u.user_guid
where u.user_guid is null;
但是,我无法通过“不存在”子查询获得正确答案:
select d.user_guid as dUserID, d.dog_guid as dDogID
from dogs d
where not exists (select distinct u.user_guid from users u);
我上面错误查询的输出:
+---------+--------+
| dUserID | dDogID |
+---------+--------+
答案查询:
select d.user_guid as dUserID, d.dog_guid as dDogID
from dogs d
where not exists (select distinct u.user_guid
from users u
where u.user_guid = d.user_guid);
答案输出:
+---------+--------------------------------------+
| dUserID | dDogID |
+---------+--------------------------------------+
| None | fd7c0a66-7144-11e5-ba71-058fbc01cf0b |
+---------+--------------------------------------+
| None | fdbb6b7a-7144-11e5-ba71-058fbc01cf0b |
+---------+--------------------------------------+
我想知道什么可能的原因是为什么在Not Exists
子句中没有u.user_guid = d.user_guid
的情况下我的where
子查询是错误的。
答案 0 :(得分:0)
因为not exists (select distinct u.user_guid from users u)
总是返回false
您可以像这样尝试NOT IN
SELECT
d.user_guid AS dUserID,
d.dog_guid AS dDogID
FROM
dogs d
WHERE
d.user_guid NOT IN (SELECT DISTINCT u.user_guid FROM user AS u);