0

嗨,我有 2 个表客户和 customer_items。现在在第二个表的两个表中都有一个 customer_id,每个客户可以有多个项目,所以表可以是这样的

id           |    item
----------------------------
1501         |    pillow
1501         |    blanket
1501         |    others
1502         |    pillow
1502         |    blanket
1502         |    others

现在我如何使用 mysql 查询选择同时拥有枕头和毯子的客户

这是我最后的方法

select custlist.id FROM customers custlist LEFT JOIN customer_items custitems ON custitems.id=custlist.id WHERE (custitems.items='pillow' AND custitems.items='blanket') UNION ALL
4

4 回答 4

1

这是一个Relational Division问题。

SELECT  a.customer_ID
FROM    customers a
        INNER JOIN customer_items b
            ON a.customer_ID = b.customer_ID
WHERE   b.item IN ('pillow', 'blanket')
GROUP   BY a.customer_ID
HAVING  COUNT(*) = 2

如果item不是每个都唯一customer_IDDISTINCT则关键字只需要计算唯一记录。

SELECT  a.customer_ID
FROM    customers a
        INNER JOIN customer_items b
            ON a.customer_ID = b.customer_ID
WHERE   b.item IN ('pillow', 'blanket')
GROUP   BY a.customer_ID
HAVING  COUNT(DISTINCT b.item) = 2
于 2013-05-30T10:00:52.840 回答
1

JW对上述解决方案的轻微变化: -

SELECT  a.customer_ID
FROM    customers a
INNER JOIN (SELECT customer_ID, item FROM customer_items WHERE item = 'pillow' GROUP BY customer_ID) PillowCheck
ON a.customer_ID = PillowCheck.customer_ID
INNER JOIN (SELECT customer_ID, item FROM customer_items WHERE item = 'blanket' GROUP BY customer_ID) BlanketCheck
ON a.customer_ID = PillowCheck.customer_ID
于 2013-05-30T10:07:41.770 回答
1

试试这个查询

SELECT 
   a.id 
FROM 
   customer_items a
INNER JOIN
   customer_items b
ON
   a.id= b.id and 
   a.item = 'PILLOW' AND 
   b.item='blanket'

如果您想要客户名称,则只需加入客户表。如果客户有多个枕头或毯子,请添加distinct

于 2013-05-30T10:18:57.173 回答
0

SELECT distinct customer_ID , item FROM customer_items WHERE item in ('PILLOW', 'blanket') GROUP BY customer_ID HAVING COUNT(item) = 2

于 2013-05-30T10:47:20.690 回答