MySQL 比较两个 SQL 表并返回缺少的 ID?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7997975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 21:32:49  来源:igfitidea点击:

Compare two SQL tables and return missing ids?

mysqlsqlexcept

提问by MilMike

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

我有两个简单的表:(这里只有“id”列)

table1:

表格1:

id
1
2
3
4

table2:

表2:

id
2
4

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

sql 查询应该比较 table2 中缺少的“id”的两个表并返回:1,2

any ideas? :) TY

有任何想法吗?:) 泰

回答by James Hill

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

回答by RedFilter

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

回答by Polynomial

Try this:

尝试这个:

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