2014-11-25 66 views
0

我有两个表:MySQL的:不存在匹配的记录

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

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

Voicemail.CustomerID releates到Customer.ID,反之亦然。

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

这是一种情况,即记录曾经存在于Voicemail表中,但此后已被删除。我现在需要找到Customer表中有VoicemailID不存在记录的所有记录。

我想:

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

但是我相信它返回的结果我想,与其中的语音邮件的实例仍然存在导致混合。

+0

我知道外键。不幸的是,原始的表设计师没有使用它们 – 2014-11-25 13:12:57

回答

1

这应该给你你想要的结果:

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

我已经追加'AND Customer.Voicemail IS NOT NULL',因为我只是在有数字的实例之后。谢谢:) – 2014-11-25 13:40:11

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; 
0

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

SELECT * 
FROM table 
WHERE NOT EXISTS(SELECT 1 
       FROM otherTable 
       WHERE table.id = otherTable.someField) 
0
select VoicemailID 
    from Customer 
    where VoicemailID not in (select id from Voicemail) 
0

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

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

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

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

请在你的回答中加上一点细节,以便它包含一些与代码相关的上下文。 – 2014-11-25 13:46:49