选择不在其他表SQL Server中的字段组合

时间:2019-02-20 17:45:32

标签: sql sql-server

假设我有这两个表:

    Table 1                        Table 2
  PName  |   FID                 PName   |  FID
  ----------------               ---------------
  Dog    |   1                   Dog     |  1
  Dog    |   2                   Cat     |  2
  Cat    |   2                   Cat     |  4
  Cat    |   3

什么是正确的查询,以选择第二个表中不存在的第一个表的两个字段组合?

我想得到的是

    Table 1                      
  PName  |   FID                 
  ----------------               
  Dog    |   2                   
  Cat    |   3

会吗?

SELECT * FROM [Table 1] WHERE ([Table 1].[PName] NOT IN (SELECT [Table 2].[PName] FROM [Table 2]) AND ([Table 1].[FID] NOT IN (SELECT [Table 2].[FID] FROM [Table 2]))

3 个答案:

答案 0 :(得分:3)

我会使用except

select * from table1
except
select * from table2

值得一提的是this great answer讨论exceptnot in,尤其是关于NULL

答案 1 :(得分:1)

我可能会建议以下内容:

select t1.* 
from table1 t1 
where not exists (select 1  
                  from table2 t2 
                  where t2.pname = t1.pname and t2.fid = t1.fid
                 );

答案 2 :(得分:1)

您需要左连接,只接受不匹配的行:

select t1.*
from t1 left join t2
on t1.pname = t2.pname and t1.fid = t2.fid
where t2.pname is null and t2.fid is null

请参见demo