use*_*670 3 mysql innodb mysql-workbench mysql-5.6 sysdba
我想找出 MySQL 中两个表的不匹配记录。
您可以使用NOT EXISTS谓词。假设你想模仿:
select a.c1, a.c2 from a
except
select b.c1, b.c2 from b
Run Code Online (Sandbox Code Playgroud)
这可以表示为:
select distinct a.c1, a.c2
from a
where not exists (
select 1 from b
where b.c1 = a.c1
and b.c2 = a.c2
)
Run Code Online (Sandbox Code Playgroud)
其他选项是使用左连接并检查空值:
select distinct a.c1, a.c2
from a
left join b
on a.c1 = b.c1
and a.c2 = b.c2
where b.c1 is null
Run Code Online (Sandbox Code Playgroud)
请注意,EXCEPT如果相同的元组存在于两个关系中并且包含空值,则这些不同。让 a = {(1,1),(2,2),(1,null)} 和 b = {(1,1),(1,null)}
select a.c1, a.c2 from a
except
select b.c1, b.c2 from b
(2,2)
Run Code Online (Sandbox Code Playgroud)
在某种意义上,EXCEPT认为 null 等于 null,而如果 a.c2 或 b.c2 为 null,则谓词 a.c2 = b.c2 的计算结果为 null,因此NOT EXISTS计算结果为 false。
select distinct a.c1, a.c2
from a
where not exists (
select b.c1, b.c2 from b where a.c1 = b.c1 and a.c2 = b.c2
)
(2,2),(1,null)
Run Code Online (Sandbox Code Playgroud)
LEFT JOIN行为类似于NOT EXISTS:
select distinct a.c1, a.c2
from a
left join b
on a.c1 = b.c1 and a.c2 = b.c2
where b.c1 is null
(2,2),(1,null)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7278 次 |
| 最近记录: |