[英]Is there a query which select which customers have bought a specific product and what other products did these same customers buy?
[英]List customers that have bought the same pair of products MySQL
我有以下兩個表:
顧客
id | customer
----|---------
1 | john
2 | jenkins
3 | jane
4 | janet
5 | jenny
產品展示
customer_id | product | price
------------|-----------|-----
1 | brush | 3.5
1 | deoderant | 1
1 | soap | 2.5
2 | bread | 3
2 | brush | 3
2 | soap | 2.5
3 | brush | 3
4 | deoderant | 1
4 | soap | 1
5 | milk | 1
因此,我必須找到購買相同產品的一對客戶,並且必須刪除重復的客戶對,並刪除諸如(john,john)的客戶對。 我創建的MySQL查詢是:
從客戶A,客戶B,產品中選擇A.customer,B.customer,products.customer_id,products.product,其中B.id = B.customer的B.id = products.customer_id和A.customer <> B.customer組;
我得到以下結果:
customer|customer|customer_id|product
--------|--------|-----------|--------
john | jane | 3 | brush
john | janet | 4 | deoderant
john | jenkins| 2 | bread
john | jenny | 5 | milk
jenkins | john | 1 | brush
我整個上午一直在與之斗爭,我被困住了。 我知道這是錯誤的,因為簡和詹金斯買了同樣的東西。
這是將客戶放入一列的一種方法:
select p.*,
group_concat(distinct c.customer) as customers
from customers c join
products p
on c.id = p.customer_id
group by p.id;
如果您實際上想要配對:
select c.id, c.customer, c2.id, c2.customer,
p.product
from customers c join
customers c2
on c.id <> c2.id join
products p
on c.id = p.customer_id join
products p2
on c2.id = p2.customer_id and
p.id = p2.id;
如果客戶可以購買同一產品多個,則可能要select distinct
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.