1

我有两个表,每个表都有以下字段:IDnumber, SectionNumber, Date。两个表中有重叠的信息。

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

4

4 回答 4

1

您可以NOT INWHERE子句中使用 a。

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)
于 2012-08-02T21:02:41.777 回答
1

哪个数据库管理系统?

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

SELECT *
FROM Table1
WHERE IDnumber NOT IN (SELECT IDnumber FROM Table2)
于 2012-08-02T21:03:03.903 回答
0
SELECT *
FROM Table1 t1 left join Table2 t2
on t1.id=t2.id
where t2.id is null
于 2012-08-03T05:01:17.387 回答
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
于 2012-08-02T21:29:05.593 回答