SQL 查询选择已购买愿望清单中所有商品的客户

问题描述 投票:0回答:4

我正在尝试编写一个查询,因为它有点复杂,所以我无法获得正确的结果。

查询的目标:获取购买了愿望清单中所有商品的客户列表?

我有 2 个表和字段,如下所示,

  1. 客户订单:

    Customer_ID
    Order_ID
    Order_date
    Product_ID
    email

  2. 愿望清单:

    Customer_ID
    Created_Date
    Product_ID

我只能编写以下查询,该查询仅检查客户从愿望清单购买的产品

select w.Customer_ID,w.Product_ID
from Wishlist w
inner join Customer_Orders od
on od.Product_ID=w.Prodcuct_ID and od.Customer_ID=w.Customer_ID

我想要的是获取那些从他们的

Wishlist
购买了所有商品的客户(Customer_ID)。

请谁能帮我知道查询应该如何进行?

mysql sql join
4个回答
2
投票

尚未购买心愿单商品的顾客。不存在版本

SELECT distinct w.Customer_ID
FROM Wishlist w
WHERE NOT EXISTS (SELECT 1 
                 FROM Wishlist wc
                 WHERE wc.Customer_ID = w.Customer_ID
                    AND NOT EXISTS (SELECT 1 
                                   FROM Customer_Orders od
                                   WHERE od.Product_ID = wc.Product_ID AND od.Customer_ID = wc.Customer_ID))

2
投票

我会使用客户聚合来表达这一点,然后断言愿望清单计数已完全满:

SELECT w.Customer_ID
FROM Wishlist w
LEFT JOIN Customer_Orders od
    ON od.Product_ID = w.Product_ID AND od.Customer_ID = w.Customer_ID
GROUP BY w.Customer_ID
HAVING COUNT(DISTINCT w.Product_ID) = COUNT(DISTINCT od.Product_ID);

如果

HAVING
子句中的断言对于某些客户失败,则意味着愿望清单中存在一个或多个产品,但在客户订单表中找到匹配项。


0
投票

是的,customer_id、product_id 在两个表中都被定义为唯一 – sfmc_newbie

SELECT Customer_ID
FROM Wishlist
LEFT JOIN Customer_Orders USING (Customer_ID, Product_ID)
GROUP BY Customer_ID
HAVING !SUM(Customer_Orders.Product_ID IS NULL)

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=352142a37fd1aaddcc6d3c20ef886d30


0
投票

Mera 午餐盒 jo h ushka 钢脂 Chuka h ushko jald se jald 替换件 Kiya Jaye

© www.soinside.com 2019 - 2024. All rights reserved.