MySQL问题

查询存在A表但不存在B表的数据

Posted by dm on July 8, 2019

SQL查询存在A表但不存在B表的数据

A表

id name age
1 xxx 15
2 yyy 18
3 zzz 20

B表

id b_id age
1 1 15
2 2 18

其中B表的b_id字段引用了A表的id字段。现在有个查询需求:

给出已知的A表中的id,比如:id in (1,2,3),找出这些id在B表中没有与之对应的记录。比如说上面A表中的id=3这条记录,B表中没有b_id与之对应

NOT IN 方法

select 
    id 
from xcb_user_infor 
where id 
not in 
(select user_id from xcb_ship_info) 
and user_type=1 
and (ship_num != '' OR ship_num IS NOT NULL); 

利用子查询

SELECT 
  a.id 
FROM
  A a 
WHERE a.id IN (1,2,3) 
  AND NOT EXISTS 
  (SELECT 
    1 
  FROM
    B b 
  WHERE b.b_id = a.id)
  

利用left join

select
    a.id
from
    A a
left join B b on a.id = b.b_id
where
    a.id IN (1, 2, 3)
and b.id is null