SQL查询以查找其他表中不存在的行

its*_*att 6 mysql sql

这就是我想要完成的事情:

我有两张桌子,先叫他们第二张.它们每个都有一个ID列.他们可能有其他列,但这些并不重要.我有第三张桌子,称之为第三张桌子.它包含两列,ID和OTHERID.OTHERID引用第一和第二表中可能存在或不存在的条目.

我想查询第三个并查找没有在第一个或第二个表中找到的OTHERID列值的行.目标是从第三个表中删除这些行.

例:

第一桌:

ID
1
2
3
Run Code Online (Sandbox Code Playgroud)

第二表:

ID
6
7
8
Run Code Online (Sandbox Code Playgroud)

第三张桌子

ID  | OTHERID
21        1
22        2
23        3
24        4
25        5
26        6
27        7
28        8
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我想要从第一个表或第二个表中没有匹配ID的第三个ID中检索ID.我希望得到以下ID:

24
25
Run Code Online (Sandbox Code Playgroud)

我尝试过的:

我已经做了一些事情来取回第三个不在第一个的条目:

select t.* from third t where not exists (select * from first f where t.otherid = f.id);
Run Code Online (Sandbox Code Playgroud)

这将使我回到以下行:

ID  | OTHERID
24        4
25        5
26        6
27        7
28        8
Run Code Online (Sandbox Code Playgroud)

同样,我可以得到不在第二位的那些:

select t.* from third t where not exists (select * from second s where t.otherid = s.id);
Run Code Online (Sandbox Code Playgroud)

我会得到:

ID  | OTHERID
21        1
22        2
23        3
24        4
25        5
Run Code Online (Sandbox Code Playgroud)

今天早上我无法理解的是如何将两个查询组合在一起以获得两个结果集之间的交集,以便只返回ID为24和25的行.那些是我可以移除的两行,因为它们是孤儿.

你怎么解决这个问题?我认为我走在正确的轨道上,但我只是在这一点上旋转没有进展.

Ser*_*Oan 15

也许这个:

SELECT third.*
FROM third
LEFT JOIN first ON third.otherID = first.id
LEFT JOIN second ON third.otherID = second.id
WHERE first.id IS NULL AND second.id IS NULL
Run Code Online (Sandbox Code Playgroud)


Aar*_*lla 8

只是用

select t.*
from third t
where 
       not exists (select * from first f  where t.otherid = f.id)
  and  not exists (select * from second s where t.otherid = s.id)
Run Code Online (Sandbox Code Playgroud)

  • 使用Serty Oan建议的LEFT OUTER JOIN会更有效率.依赖子查询(例如"不存在"子句中使用的子查询)必须每行执行一次,而LEFT OUTER JOIN查询只需扫描一次.(MySQL 5.x) (2认同)