SQL在两个表中查找不匹配的值

SQL在两个表中查找不匹配的值,sql,join,match,Sql,Join,Match,我有两个表,试图从表1返回一条与表2中特定值不匹配的记录。我想知道表1中没有参加表2中特定课程的每个人。在这个例子中,我想知道每个没有上过A课程的人。结果应该是ID的3和5。提前谢谢 Table1 ID Name 1 John 2 Jane 3 Joe 4 Jack 5 Jill Table2 ID Class 1 A 1 B 3 D 2 A 4 A 5 D 不在脑海中: select t.* from table1 t1 where

我有两个表,试图从表1返回一条与表2中特定值不匹配的记录。我想知道表1中没有参加表2中特定课程的每个人。在这个例子中,我想知道每个没有上过A课程的人。结果应该是ID的3和5。提前谢谢

Table1  
ID  Name
1   John
2   Jane
3   Joe
4   Jack
5   Jill

Table2  
ID  Class
1   A
1   B
3   D
2   A
4   A
5   D

不在
脑海中:

select t.*
from table1 t1
where t1.id not in (select t2.id from table2 t2 where t2.class = 'A');
实际上,我宁愿
不存在

select t.*
from table1 t1
where not exists (select t2.id from table2 t2 where t2.class = 'A' and t2.id = t1.id);

您还可以使用
左连接

不在
脑海中:

select t.*
from table1 t1
where t1.id not in (select t2.id from table2 t2 where t2.class = 'A');
实际上,我宁愿
不存在

select t.*
from table1 t1
where not exists (select t2.id from table2 t2 where t2.class = 'A' and t2.id = t1.id);

您还可以使用
左连接

您也可以使用
左连接
。下面的查询将为您提供所需的答案:

SELECT t1.Id 
FROM Table1 t1
LEFT JOIN Table2 t2
    ON t1.Id = t2.Id AND t2.Class = 'A'
WHERE t2.Id IS NULL
演示:


您也可以使用
左连接。下面的查询将为您提供所需的答案:

SELECT t1.Id 
FROM Table1 t1
LEFT JOIN Table2 t2
    ON t1.Id = t2.Id AND t2.Class = 'A'
WHERE t2.Id IS NULL
演示: