Mysql 仅显示同时具有两种类型记录和仅具有这些记录的客户

Mysql 仅显示同时具有两种类型记录和仅具有这些记录的客户,mysql,sql,Mysql,Sql,如何在MySQL中执行以下操作- 我有一个包含客户订单的数据库,我只想显示两种类型的订单以及这两种类型的订单的客户记录 范例- Orders: 'Customer Id' 'Product' 0001 Widget 1 0001 Widget 2 0001 Widget 3 0002 Widget 2 0002 Widget 3

如何在MySQL中执行以下操作- 我有一个包含客户订单的数据库,我只想显示两种类型的订单以及这两种类型的订单的客户记录

范例-

  Orders:
    'Customer Id'   'Product'
    0001            Widget 1
    0001            Widget 2
    0001            Widget 3
    0002            Widget 2
    0002            Widget 3
    0003            Widget 1
    0004            Widget 1
    0004            Widget 3
    0004            Widget 4
    0004            Widget 5
我只想显示订购了小部件1和小部件3的客户,并且只显示这些订单

预期结果-

  Orders:
    'Customer Id'   'Product'
    0001            Widget 1
    0001            Widget 3
    0004            Widget 1
    0004            Widget 3

尝试将订单与小部件列表连接起来,同时强制组中的行数与列表中的行数相同

SELECT
    X.*
FROM
    Orders X
    INNER JOIN (
        SELECT
            O.`Customer Id`
        FROM
            Orders O
            LEFT JOIN (
                SELECT 'Widget 1' Product
                UNION ALL
                SELECT 'Widget 3' Product
            ) P ON O.Product = P.Product
        GROUP BY
            O.`Customer Id`
        HAVING
            COUNT(P.product) = COUNT(1)
    ) M ON X.`Customer Id` = M.`Customer Id`

请将客户Id更改为客户Id,列名中的空格不是一个好主意

我将使用聚合:

select o.customer_id
from orders o
group by o.customer_id
having sum( (product = 'Widget 1') ) > 0 and
       sum( (product = 'Widget 3') ) > 0 and
       sum( (product not in ('Widget 1', 'Widget 3')) );
我认为没有理由自己退回产品,但如果你真的想要,你可以添加group_concatproduct

如果需要原始行,可以使用上面的行进行过滤。或:

select o.*
from orders o
where o.product in ('Widget 1', 'Widget 3') and
      not exists (select 1
                  from orders o2
                  where o2.customer_id = o.customer_id and
                        o2.product not in ('Widget 1', 'Widget 3')
                 );
这个怎么样:

SELECT custid, product FROM transactions WHERE custid IN 
(SELECT custid
FROM transactions
WHERE product in ('w1', 'w3')
GROUP BY custid
HAVING COUNT(DISTINCT product) = 2) 
and product IN('w1', 'w3');

您使用的是什么数据库引擎?SQL Server,MySQL???MySQL对不起,我不认为这会有什么不同,我会更新这个问题
SELECT custid, product FROM transactions WHERE custid IN 
(SELECT custid
FROM transactions
WHERE product in ('w1', 'w3')
GROUP BY custid
HAVING COUNT(DISTINCT product) = 2) 
and product IN('w1', 'w3');