简体   繁体   English

SQL:选择表A中不在表B中的所有唯一值

[英]SQL: select all unique values in table A which are not in table B

I have table A 我有桌子A.

Id  | Name      | Department
-----------------------------
0   | Alice     | 1
0   | Alice     | 2
1   | Bob       | 1

and table B 和表B.

Id  | Name
-------------
0   | Alice     

I want to select all unique Ids in table A which do not exist in table B. how can I do this? 我想在表A中选择表B中不存在的所有唯一ID。我该怎么做?

select distinct id 
from TableA a
where not exists (
    select id 
    from TableB 
    where id = a.id
)

Just to provide a different solution than NOT IN : 只是为了提供与NOT IN不同的解决方案:

SELECT DISTINCT A.Id
FROM A
LEFT OUTER JOIN B
    ON A.Id = B.Id
WHERE B.Id IS NULL

The "good" solution is usually MINUS or EXCEPT, but MySQL doesn't support it. “好”解决方案通常是MINUS或EXCEPT,但MySQL不支持它。

This question was asked a few time ago and someone posted an article comparing NOT IN, NOT EXISTS and LEFT OUTER JOIN ... IS NULL. 这个问题是在几年前被问到的,有人发布了一篇文章,比较NOT IN,NOT EXISTS和LEFT OUTER JOIN ...... IS NULL。 It would be interesting if someone could find it again! 如果有人能再找到它会很有趣!

The most efficient answer is to use a left join, as using "NOT IN" can sometimes prevent a query from using an index, if present. 最有效的答案是使用左连接,因为使用“NOT IN”有时可以防止查询使用索引(如果存在)。

The answer in this case would be something like 在这种情况下的答案将是这样的

SELECT DISTINCT 
    * 
FROM 
    TableA a 
LEFT JOIN 
    TableB b
ON 
    a.Id = b.Id 
WHERE 
    b.Id IS NULL

Alternatively, this is more readable than a left join, and more efficient than the NOT IN solutions 或者,这比左连接更易读,并且比NOT IN解决方案更有效

SELECT * FROM TableA a where NOT EXISTS (SELECT * FROM TableB where Id = a.Id)

I'd use a NOT EXISTS Like this: 我使用NOT EXISTS这样:

SELECT A.Id
FROM TableA A
WHERE NOT EXISTS (SELECT B.Id FROM TableB B WHERE A.Id = B.Id)
GROUP BY A.Id
SELECT DISTINCT Id FROM A WHERE Id NOT IN (SELECT ID FROM B);
SELECT DISTINCT Id FROM A WHERE Id NOT IN(SELECT DISTINCT Id FROM B);

The subquery will get all the IDs in B. The group by...having will get all the unique IDs in A that are also not in B. 子查询将获得B中的所有ID group by...having所有ID将获得A中也不在B中的所有唯一ID。

select *
from A 
where id not in
(
    select distinct id
    from B
)
group by ID
having count(*) > 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM