Mysql SQL-找到购买了2种特定产品的客户
在SQL中,我需要以下方面的帮助: 我有3个表,其中包含以下数据: 表名:客户 客户ID-1,2,3,4,5,6 客户名称-客户1、客户2、客户3、客户4、客户5、客户6 表名:事务处理 交易ID-1,2,3,4,5,6,7,8 产品ID-2,2,3,4,2,1,4,2 客户ID-1,2,4,4,5,6,2,5 表名:产品 产品标识-1,2,3,4 产品名称-产品1、产品2、产品3、产品4 我想知道哪些客户购买了产品3和4-结果应该是ID为4的客户 我有下面的几行,但是由于IN功能意味着显示客户ID 4和客户ID 2,它只适用于3或4。我不确定在此场景中在何处使用AND函数Mysql SQL-找到购买了2种特定产品的客户,mysql,sql,Mysql,Sql,在SQL中,我需要以下方面的帮助: 我有3个表,其中包含以下数据: 表名:客户 客户ID-1,2,3,4,5,6 客户名称-客户1、客户2、客户3、客户4、客户5、客户6 表名:事务处理 交易ID-1,2,3,4,5,6,7,8 产品ID-2,2,3,4,2,1,4,2 客户ID-1,2,4,4,5,6,2,5 表名:产品 产品标识-1,2,3,4 产品名称-产品1、产品2、产品3、产品4 我想知道哪些客户购买了产品3和4-结果应该是ID为4的客户 我有下面的几行,但是由于IN功能意味着显示客户
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)`
谢谢
Vishal您需要这个,而不是在
where p.product ID = '3' AND p.product ID ='4'
IN在值之间使用OR逻辑,这就是为什么要同时返回这两个值的原因一个可能的查询如下所示。内部子查询只提取拥有这两个产品的客户(见最后一个,其中A.RC=2),模拟您需要的“和条件”
SELECT DISTINCT A.customer_ID, C.customer_Name
FROM (SELECT customer_ID, COUNT(DISTINCT product_ID) AS RC
FROM transactions
WHERE t.product ID IN (3,4)
GROUP BY customer_ID) A
INNER JOIN transactions t ON A.customer_ID = t.customer_ID
LEFT JOIN customer c on c.customer ID = A.customer ID
LEFT JOIN product p on p.product ID = A.product ID
WHERE A.RC=2 AND t.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 c.CustomerName
from Customer c join Transacation t
on c.Customer_ID = t.Customer_ID
where Product_ID in (3,4)
group by c.CustomerName
having count(distinct Product_ID) = 2
另一种方式,但不是最理想的:
select *
from customer
where customer_id in (select customer_id from transactions where product_id = 3
INTERSECT
select customer_id from transactions where product_id = 4);
请参阅formatJOIN、GroupBy、HAVING、COUNT、DISTINCT表中的Post示例数据和预期结果。为什么要使用联接?从需要数据的表中选择(此处仅表
customer
)。将条件放入WHERE
子句中(在中使用[NOT]或[NOT]EXISTS
进行查找,在您的情况下,在事务
上)。谢谢,这看起来像是我正在寻找的解决方案-我将给出一个goI。我使用了第二个goI,对事务表进行了单次查询,效果非常好,我一直以为我需要加入!谢谢
select *
from customer
where customer_id in (select customer_id from transactions where product_id = 3
INTERSECT
select customer_id from transactions where product_id = 4);