Compare two SQL tables and return missing ids?

China☆狼群 提交于 2019-12-03 12:23:46

问题


I have two simple tables: (here only the "id" column)

table1:

id
1
2
3
4

table2:

id
2
4

the sql query should compare the two tables for missing "id" in table2 and return: 1,2

any ideas? :) TY


回答1:


There are several ways to skin this cat:

SELECT    table1.ID
FROM      table1
WHERE     table1.ID NOT IN(SELECT table2.ID FROM table2)

Or you could use a left outer join:

SELECT          table1.ID
FROM            table1
LEFT OUTER JOIN table2 ON table1.ID = table2.ID
WHERE           table2.ID IS NULL



回答2:


select t1.*
from table1 t1
left outer join table2 t2 on t1.id = t2.id
where t2.id is null



回答3:


Try this:

SELECT    table1.id
FROM      table1
WHERE     table1.id NOT IN(SELECT table2.id FROM table2)


来源:https://stackoverflow.com/questions/7997975/compare-two-sql-tables-and-return-missing-ids

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!