匹配来自两个不同表的值

时间:2012-10-10 18:31:15

标签: mysql sql match

给定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

2 个答案:

答案 0 :(得分:5)

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

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

请参阅SQL Fiddle with Demo

如果您只想比较值:

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

请参阅SQL Fiddle with Demo

答案 1 :(得分: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 demo