【问题标题】:MySQL: matching records that don't existMySQL:匹配不存在的记录
【发布时间】:2014-11-25 13:10:03
【问题描述】:

我有两张桌子:

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

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

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

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

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

我试过了:

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

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

【问题讨论】:

  • 我知道外键。不幸的是,最初的表格设计者没有使用它们

标签: mysql


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 我也不得不追加AND Customer.Voicemail IS NOT NULL,因为我只是在有数字的实例之后。谢谢你:)
    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:
        select VoicemailID
        from Customer
        where VoicemailID not in (select id from Voicemail)
      

      【讨论】:

        【解决方案5】:

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

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

        【讨论】:

          【解决方案6】:

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

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

          【讨论】:

          • 请详细说明您的答案,以便它包含一些上下文,因为它是纯代码的。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多