MySQL:匹配不存在的记录

时间:2014-11-25 13:10:03

标签: mysql

我有两张桌子:

Customer
+---+-----------+
|ID |VoicemailID|

Voicemail
+---+----------+
|ID |CustomerID|

Voicemail.CustomerIDCustomer.ID相关,反之亦然。

如何从客户表中选择行,其中Customer.VoicemailID不再是Vo icemail表中的有效记录?

这种情况下,记录曾经存在于Voicemail表中,但后来被删除了。我现在需要查找Customer表中具有VoicemailID不存在记录的所有记录。

我试过了:

SELECT DISTINCT Customer.ID, Customer.VoicemailID
FROM Customers LEFT JOIN Voicemail ON Customer.VoicemailID <> Voicemail.ID

但是我相信它会返回我想要的结果,并混入语音邮件实例仍然存在的结果。

6 个答案:

答案 0 :(得分:2)

您使用LEFT JOIN走在正确的轨道上。但是你需要寻找匹配,然后在失败时返回:

SELECT c.ID, c.VoicemailID
FROM Customer c LEFT JOIN
     Voicemail v
     ON c.VoicemailID = v.ID
WHERE v.ID IS NULL;

答案 1 :(得分:1)

这可以为您提供所需的结果:

SELECT Customer.ID, Customer.VoicemailID
FROM Customer
   LEFT JOIN Voicemail ON Voicemail.ID = Customer.VoicemailID
WHERE Voicemail.ID IS NULL

答案 2 :(得分:0)

您可以使用子查询并查找不存在的行。检查MySQL documentationWHERE NOT EXISTS的语法:

SELECT *
FROM table
WHERE NOT EXISTS(SELECT 1
                 FROM otherTable 
                 WHERE table.id = otherTable.someField )

答案 3 :(得分:0)

  select VoicemailID
  from Customer
  where VoicemailID not in (select id from Voicemail)

答案 4 :(得分:0)

您可以使用像这样的相关子查询

select * from customer a
 where not exists (select 1 from voicemail b 
                    where b.id = a.voicemailid)

答案 5 :(得分:0)

这是[PHP:5.5.3]中的正确查询,我在Xampp 1.8.3中使用phpMyAdmin。

SELECT * FROM Customer 
WHERE Customer.VoicemailID NOT IN (SELECT ID FROM Voicemail)