如何通过检查另一个表来排除某些数据库记录

时间:2015-04-08 10:00:36

标签: mysql sql database

我目前有这个简单的SQL语句来提取我们购物车上最近100个引号的详细信息:

SELECT
    *
FROM
    orders
JOIN customers ON orders.CustomerNumber = customers.CustomerNumber
WHERE
    STATUS = 'QUOTE'
ORDER BY
    orders.OrderNumber DESC
LIMIT 0,
 100

我们还有一个“评论”表,有时我们的员工会添加一组评论,说客户不希望被联系。如何修改我的SQL以交叉检查注释表以查看是否存在与订单号相关联的评论?

  • 表名:评论
  • 列: OrderNumber(用于连接),CommentText
  • 评论如果存在,则从记录集中查找和排除:“不要 联系“

谢谢!

2 个答案:

答案 0 :(得分:4)

一种选择是使用not exists谓词:

SELECT
    *
FROM
    orders o
JOIN customers c ON o.CustomerNumber = c.CustomerNumber
WHERE
    STATUS = 'QUOTE'
AND NOT EXISTS (
    SELECT * FROM comments 
    WHERE CommentText = 'Do not contact' 
    AND OrderNumber = o.OrderNumber 
)
ORDER BY
    o.OrderNumber DESC
LIMIT 0, 100

Sample SQL Fiddle

答案 1 :(得分:1)

SELECT    * 
FROM orders
JOIN customers ON orders.CustomerNumber = customers.CustomerNumber
JOIN comments ON orders.orderNumber = comments.orderNumber
WHERE STATUS = 'QUOTE'
and comments.commentText NOT LIKE '%Do not contact%'
ORDER BY orders.OrderNumber DESC
LIMIT 0, 100