2

给定 2 个表,TableA 和 TableB,当“值”与 TableB 的任何“值”都不匹配时,如何获取 TableA 的“id”?

表 A

+----+-------+
| id | value |
+----+-------+
| 1  |   a   |
| 2  |   b   |
| 3  |   c   |
| 4  |   d   |
| 5  |   e   |
+----+-------+

表 B

+----+-------+
| id | value |
+----+-------+
| 1  |   a   |
| 2  |   b   |
| 3  |   c   |
| 4  |   c   |
| 5  |   f   |
+----+-------+

结果表

+----+
| id |
+----+
| 4  |
| 5  |
+----+

已编辑(SQLFiddle): http ://sqlfiddle.com/#!2/4c8c9

4

2 回答 2

5

如果要验证两个表中的 id/值是否相同,请使用:

select distinct id
from tablea
where (id, value) not in (select id, value
                          from tableb)

请参阅带有演示的 SQL Fiddle

如果您只想比较值:

select distinct id
from tablea
where (value) not in (select value
                          from tableb)

请参阅带有演示的 SQL Fiddle

于 2012-10-10T18:35:28.083 回答
3
select a.id
from tableA a
left outer join tableB b on a.id = b.id and a.value = b.value
where a.id is not null and b.value is null

SQLFiddle 演示

于 2012-10-10T18:33:40.257 回答