MySQL:查找另一个表中不存在的记录

时间:2015-02-13 21:21:08

标签: mysql

我有2个MySQL表:

id   customer  ipAddress
--------------------------
1    acme      10.10.10.10
2    target    33.33.33.33

number   ip
--------------------
54321    10.10.10.10
41247    33.33.33.33
62068    77.77.77.77

在这种情况下,77.77.77.77在表1中没有条目。

如何获得表2中表1中没有ipAddress的所有数字?

我试过了:

select ip from table1,table2 where ip not in(select ipAddress from table1);

但我得到一个空集。

2 个答案:

答案 0 :(得分:3)

我得到了一个正确答案(77.77.77.77)left joinwhere is null

select ip from table2 left join table1 on (ip = ipAddress) where ipAddress is null;

答案 1 :(得分:0)

无匹配的记录”问题经常可以通过简单OUTER JOIN然后WHERE ... IS NULL来解决。

在你的情况下:

SELECT t2.ip
FROM table1 t1
RIGHT JOIN table2 t2 ON t1.ipAddress = t2.ip
WHERE t1.ipAddress IS NULL ;

SQL Fiddle DEMO