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

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) for john 的对。我创建的 MySQL 查询是:

selectA.customer,B.customer,products.customer_id,products.product来自客户A,客户B,产品where B.id = products.customer_id 和 A.customer <> B.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