如何在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
答案 0 :(得分:0)
尝试将订单与窗口小部件列表一起加入,同时强制组中的行数与列表中的行数相同。
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`
答案 1 :(得分:0)
SELECT *
FROM ORDERS O1, ORDERS O2
WHERE O1.customer_id = O2.customer_id
AND ( O1.Product = "Widget 1"
AND O2.Product = "Widget 3" )
OR (O1.Product = "Widget 3"
AND O2.Product = "Widget 1")
AND O1.customer_id NOT IN (
SELECT customer_id
FROM ORDERS O3, ORDERS O4
WHERE O3.customer_id = O4.customer_id
AND (O3.Product <> "Widget 1"
OR O4.Product <> "Widget 3")
OR (O3.Product <> "Widget 3"
OR O4.Product <> "Widget 1")
)
请将“客户ID”更改为“ customer_id”,列名中的空格不是一个好主意
答案 2 :(得分:0)
我将使用聚合:
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_concat(product)
。
如果要原始行,可以使用以上内容进行过滤。或者:
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')
);
答案 3 :(得分:0)
如何?
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');