SQL查询来查找ID不在另一个表中的logging
我有两个表绑定主键在数据库中,我希望find他们之间的不相交集。 例如,
-
Table1
有列(ID, Name
)和样本数据:(1 ,John), (2, Peter), (3, Mary)
-
Table2
具有列(ID, Address
)和采样数据:(1, address2), (2, address2)
ID, Address
(1, address2), (2, address2)
ID, Address
(1, address2), (2, address2)
那么如何创build一个SQL查询,以便我可以从table1
中获取不在table2
ID的行。 在这种情况下, (3, Mary)
应该被退回?
PS。 ID是这两个表的主键。
提前致谢。
尝试这个
SELECT ID, Name FROM Table1 WHERE ID NOT IN (SELECT ID FROM Table2)
使用LEFT JOIN
SELECT a.* FROM table1 a LEFT JOIN table2 b on a.ID = b.ID WHERE b.id IS NULL
记住@John Woo的评论/链接上面提到的几点,这是我通常会处理的:
SELECT t1.ID, t1.Name FROM Table1 t1 WHERE NOT EXISTS ( SELECT TOP 1 NULL FROM Table2 t2 WHERE t1.ID = t2.ID )
我运行了一些testing(在Postgres 9.5上),每个testing使用两个〜2M行的表。 下面的查询至less比其他提议的查询执行5 *
-- Count select count(*) from ( (select id from table1) except (select id from table2) ) t1_not_in_t2; -- Get full row select table1.* from ( (select id from table1) except (select id from table2) ) t1_not_in_t2 join table1 on t1_not_in_t2.id=table1.id;
SELECT COUNT(ID) FROM tblA a WHERE a.ID NOT IN (SELECT b.ID FROM tblB b) --For count SELECT ID FROM tblA a WHERE a.ID NOT IN (SELECT b.ID FROM tblB b) --For results