检索主表中不存在的数据,仅存在于辅助表中

时间:2015-09-07 05:57:09

标签: sql sql-server

问题: 我想检索列表b中不存在的值,但它存在于表a。

我不知道该怎么做。

请记住,数据会经常变化。

SELECT [id]
      ,[name]
      ,[email]
      ,[phone]
      ,[cellphone]
      ,[none]
  FROM [test].[dbo].[datatable]

SELECT [id]
      ,[name]
      ,[email]
      ,[phone]
      ,[cellphone]
      ,[none]
  FROM [test].[dbo].[datatable2]

enter image description here

2 个答案:

答案 0 :(得分:1)

在表格上使用LEFT OUTER join
请在下面找到示例查询:

select a.* 
from tableA a
Left outer join TableB b
on a.id=b.id
where b.id is NULL

答案 1 :(得分:0)

如果您想查看整行是否匹配,可以使用EXCEPT查找结果集。

SELECT [id],
    [name],
    [email],
    [phone],
    [cellphone],
    [none]
FROM [test].[dbo].[datatable]
EXCEPT
SELECT [id],
    [name],
    [email],
    [phone],
    [cellphone],
    [none]
FROM [test].[dbo].[datatable2]

如果您只担心密钥,我喜欢使用NOT EXISTS来获取结果集。

SELECT [id],
    [name],
    [email],
    [phone],
    [cellphone],
    [none]
FROM [test].[dbo].[datatable] t1
WHERE NOT EXISTS (SELECT 1 FROM [test].[dbo].[datatable2] t2 WHERE t2.[id] = t1.[id])