如何编写SQL语句从一个表中选择第二个表中没有对应记录的记录。
示例:有两个表a
和b
.
a (id, first, second, third)
b (id, whatever)
我应该从表中选择所有数据a
,没有记录在哪里a.id = b.id
。不应选择该记录。
SELECT * FROM a WHERE id NOT IN (SELECT id FROM b)
带有 EXISTS 子查询:
SELECT *
FROM a
WHERE NOT EXISTS (SELECT 1 FROM b WHERE b.id=a.id)
没有子查询:
SELECT *
FROM a
LEFT JOIN b ON b.id=a.id
WHERE b.id is null
GROUP BY a.id
select * from a where a.id not in (select distinct id from b)