gpt4 book ai didi

mysql - SQL - 寻找购买了 2 种特定产品的客户

转载 作者:行者123 更新时间:2023-11-29 03:47:40 26 4
gpt4 key购买 nike

我需要一些 SQL 方面的帮助:

我有 3 个表,其中包含以下数据:

表名:客户

客户 ID - 1,2,3,4,5,6

客户姓名-客户1、客户2、客户3、客户4、客户5、客户6

表名:transactions

交易ID -1, 2,3,4,5,6,7,8

产品编号 - 2,2,3,4,2,1,4,2

客户 ID - 1,2,4,4,5,6,2,5

表名:product

产品编号 - 1,2,3,4

产品名称 - 产品 1、产品 2、产品 3、产品 4

我想知道哪些客户购买了产品 3 和 4 - 结果应该只是 ID 为 4 的客户。

我有下面几行,但是由于 IN 函数,它只适用于 3 或 4,这意味着显示客户 ID 4 和客户 ID 2。我不确定在这种情况下在哪里使用 AND 函数

select distinct c.customer ID
, c.customer Name
FROM transactions t
LEFT
JOIN customer c
on c.customer ID = t.customer ID
LEFT
JOIN product p
on p.product ID = t.product ID
where p.product ID IN (3,4)`

谢谢

维沙尔

最佳答案

直截了当:选择同时属于产品 3 买家和产品 4 买家的客户:

select * 
from customer
where customer_id in (select customer_id from transactions where product_id = 3)
and customer_id in (select customer_id from transactions where product_id = 4);

但是,仅查询交易表一次(通过按客户汇总)通常更快。

select * 
from customer
where customer_id in
(
select customer_id
from transactions
where product_id in (3,4)
group by customer_id
having count(distinct product_id) = 2
);

关于mysql - SQL - 寻找购买了 2 种特定产品的客户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46525006/

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