gpt4 book ai didi

mysql - 与 MySQL NOT EXISTS 作斗争

转载 作者:行者123 更新时间:2023-11-29 11:57:36 25 4
gpt4 key购买 nike

我正在尝试查询我们的数据库以提取客户数据。关键部分是:

提取所有未购买product_a的客户/订单。

这将列出已购买product_b、product_c 和product_d 的客户/订单。

但它需要确保客户从未购买过product_a。我需要排除它们。

这是处理 NOT EXISTS 的正确方法吗?我仍然觉得其中包含一些购买了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,也可以包含客户记录,对吗?

最佳答案

Your Not Exists 有点不对劲,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 NOT EXISTS 作斗争,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32952520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com