在一个不在另一个表中的表中查找什么

时间:2017-12-05 22:25:26

标签: sql sql-server-2008

我有以下两个表:

CREATE TABLE TEMP1(ID INT)
CREATE TABLE TEMP2(ID INT)

INSERT INTO TEMP1 SELECT 1
INSERT INTO TEMP1 SELECT 2
INSERT INTO TEMP1 SELECT 3
INSERT INTO TEMP1 SELECT 4

INSERT INTO TEMP2 SELECT 1
INSERT INTO TEMP2 SELECT 2
INSERT INTO TEMP2 SELECT 3
INSERT INTO TEMP2 SELECT 4
INSERT INTO TEMP2 SELECT 5

SELECT * FROM TEMP1
SELECT * FROM TEMP2

我试图找到TEMP2中的记录,但不是TEMP1中的记录,即5。 如果我运行以下查询,我会得到正确的结果:

  SELECT DISTINCT [ID2] FROM (
   SELECT DISTINCT
   C1.[ID] AS [ID1]
   ,C2.[ID] AS [ID2]
   FROM TEMP1 C1
   FULL JOIN TEMP2 C2 ON C1.[ID]=C2.[ID]
   )A
   WHERE [ID1] IS NULL
   ORDER BY 1

但是当我运行以下查询时,我不会返回任何内容:

   SELECT DISTINCT T2.[ID] FROM TEMP2 T2
   WHERE T2.[ID] NOT IN (SELECT DISTINCT T1.[ID] FROM TEMP1 T1 )
   ORDER BY 1

任何想法都错了吗?

3 个答案:

答案 0 :(得分:1)

不要将not in与子查询一起使用。它没有正确的语义。如果子查询中的一个值为NULL,则不返回任何行。请改用not exists

SELECT T2.[ID]
FROM TEMP2 T2
WHERE NOT EXISTS (SELECT 1 FROM TEMP1 T1 WHERE T2.[ID] = T1.[ID])
ORDER BY 1;

我假设外部查询中不需要SELECT DISTINCT

答案 1 :(得分:1)

您可以使用左连接并测试null:

SELECT DISTINCT T2.ID 
   FROM TEMP2 T2 
      LEFT JOIN TEMP1 T1 USING(ID) 
   WHERE T1.ID IS NULL;

答案 2 :(得分:1)

我建议您使用 EXCEPT

select ID from TEMP2
EXCEPT
Select ID from TEMP1