列出已购买同一对产品MySQL的客户

时间:2015-03-06 15:33:55

标签: mysql mysql-workbench

我有以下两个表:

客户

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

因此,我必须找到购买相同产品的那对客户,我必须删除重复对并删除对象(如约翰,约翰)为约翰。我创建的MySQL查询是:

选择A.customer,B.customer,products.customer_id,products.product from customer A,customer B,products where B.id = products.customer_id和A.customer<> B.customer的B.customer group;

我得到以下结果:

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

整个上午我一直在与此作斗争,我被卡住了。我知道这是错的,因为简和詹金斯买了同样的物品。

1 个答案:

答案 0 :(得分:2)

这是一种将客户放入一列的方法:

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