我正在尝试查询我们的数据库以提取客户数据。关键部分是:
撤出所有尚未购买product_a的客户/订单。
这将列出已购买的客户/订单product_b,product_c和product_d。
但是需要确保客户从未购买过product_a。我需要排除它们。
这是解决“不存在”的正确方法吗?我仍然觉得其中包括购买了product_a的一些记录。
SELECT
*
FROM
orders
JOIN customers AS cus ON orders.CustomerNumber = cus.CustomerNumber
WHERE
product != 'product_a'
OR (
HomeTelephone = ''
AND MobileTelephone != ''
)
AND NOT EXISTS (
SELECT
OrderNumber
FROM
orders AS o
JOIN customers AS c ON o.CustomerNumber = c.CustomerNumber
WHERE
c.EmailAddress = cus.EmailAddress
AND Product = 'product_a'
AND completed = 1
)
ORDER BY
orderdate
如果没有NOT EXISTS语句,即使他们单独购买了product_a,也可以包括客户记录,对吗?
最佳答案
您的“不存在”有点差,where product != 'product_a'
是多余的。
SELECT
*
FROM
orders AS o1
JOIN customers AS cus ON o1.CustomerNumber = cus.CustomerNumber
WHERE
cus.HomeTelephone = ''
AND cus.MobileTelephone != ''
AND NOT EXISTS (
SELECT
1
FROM
orders o2
WHERE
o2.CustomerNumber = cus.CustomerNumber
AND Product = 'product_a'
AND completed = 1
)
ORDER BY
o1.orderdate
这将为您提供客户的订单。但是,根据您的描述,如果只需要客户信息,则可以在查询的第一部分中排除对订单的联接,并使用“不存在”来确定该客户是否购买了product_a。
SELECT
*
FROM
customers cus
WHERE
HomeTelephone = ''
AND MobileTelephone != ''
AND NOT EXISTS (
SELECT
1
FROM
orders o
WHERE
o.CustomerNumber = cus.CustomerNumber
AND Product = 'product_a'
AND completed = 1
)
关于mysql - 与MySQL斗争不存在,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32952520/