【问题标题】:How to use the exists operator properly in mysql?如何在mysql中正确使用exists运算符?
【发布时间】:2014-06-06 03:40:24
【问题描述】:

我想让 EXISTS 运算符列出没有订单的客户名称

所以我有两个表(如下所示),一个名为 Customer,其中包含 CustomerName 和 CustomerID,另一个命名为包含 CustomerID 和 OrderID 的订单。我正在尝试

选择客户名称、客户 ID 来自客户 存在于何处(

选择客户 ID、订单 ID 来自订单 WHERE OrderID CustomerID );

但它并没有按照我想要的方式工作。

【问题讨论】:

  • 您的问题取决于“我想要的方式”是什么意思。最好告诉我们。

标签: mysql sql subquery exists


【解决方案1】:

一种方法是使用 NOT EXISTS 语法。就我个人而言,这对我来说更有意义。我认为这个查询对你有用:

Select CustomerName
, CustomerID 
FROM Customer C 
WHERE NOT EXISTS(Select 1 FROM Orders O where C.CustomerId = O.CustomerId)

【讨论】:

  • 你是对的。第二个查询不会提供预期的结果。已编辑和删除。
【解决方案2】:

“NOT EXISTS”是出了名的糟糕表现(除非 MySQL 对其进行了某种优化),因为 if 会强制进行全表扫描。

标准的解决方法是使用外连接。不直观,因此应该为未来的维护者评论。

SELECT CustomerName, CustomerID from Customer C LEFT JOIN Orders O ON C.CustomerID = O.CustomerID WHERE O.CustomerID IS NULL

【讨论】:

    猜你喜欢
    • 2020-09-03
    • 2012-01-19
    • 2021-10-12
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多