从表中选择不在另一个表中

时间:2012-08-02 21:00:36

标签: sql sql-server

我有两个表,每个表都包含以下字段:IDnumberSectionNumberDate。两个表中有重叠的信息。

如何仅选择不重叠的行(即在一个表中而不是在另一个表中)?

4 个答案:

答案 0 :(得分:1)

您可以在NOT IN条款中使用WHERE

SELECT IDnumber, SectionNumber, Date
FROM table1
WHERE IDnumber NOT IN (SELECT IDnumber FROM table2)

NOT EXISTS

SELECT IDnumber, SectionNumber, Date
FROM table1 t1
WHERE NOT EXISTS (SELECT IDnumber FROM table2 t2 WHERE t1.IDnumber = t2.IDnumber)

答案 1 :(得分:1)

哪个DBMS?

如果是SQL Server,那么它几乎就是你在标题中写的......

SELECT *
FROM Table1
WHERE IDnumber NOT IN (SELECT IDnumber FROM Table2)

答案 2 :(得分:0)

如果要比较多个列,则需要外部联接:

select table1.*
from table1 left outer join
     table2
     on table1.id = table2.id and
        table1.SectionNumber = table2.SectionNumber and
        table1.date = table2.date
where table2.id is null

如果表之间可能有多个匹配项,则连接可能效率低下。假设您只想要这三个字段,您可以使用避免连接的技巧:

select id, SectionNumber, date
from ((select 0 as IsTable2, id, SectionNumber, date
       from table1
      ) union all
      (select 1 as IsTable2, id, SectionNumber, date
       from table2
      )
     ) t
 group by id, SectionNumber, date
 having max(isTable2) = 0

答案 3 :(得分:0)

SELECT *
FROM Table1 t1 left join Table2 t2
on t1.id=t2.id
where t2.id is null