【SQL】查询存在于一个表而不存在于另外一个表的数据

发布时间 2023-03-22 21:11:14作者: lihewei

需求描述:A、B两表,找出ID字段中,存在A表,但是不存在B表的数据。

-- 1、方法一(推荐):使用not exists函数,括号内select 1查A与B的id能关联上的,然后查A表not exists的
select * from A a where not exists (select 1 from B b where b.id = a.id)

-- 2、方法二(推荐):使用 left join , “B.ID isnull” 表示左连接之后在B.ID 字段为 null的记录
select A.ID from A left join B on A.ID=B.ID where B.ID is null

-- 3、方法三(不推荐):子查询的方式(慢)
select * from B where (select count(1) as num from A where A.ID = B.ID) = 0   

-- 4、方法四(不推荐):使用 not in ,容易理解,效率低
select A.ID from A where A.ID not in (select ID from B)