创建SQL语句以返回购买多个项目的用户ID

时间:2012-01-15 15:07:06

标签: mysql sql

我确信解决方案很简单,但它会让我厌烦。

表的配置如下:

TABLE NAME = sales
Field 1 = id INT Auto Increment Primary Key
Field 2 = user_id INT NOT NULL
Field 3 = item VARCHAR(100) NOT NULL

因此,假设我正在寻找购买了以下商品的用户:

  • 的iPod
  • 自行车

如何构建SQL语句以返回已购买三个项目(用户必须已购买所有三个项目)的用户的user_id值?

3 个答案:

答案 0 :(得分:3)

加入每个项目的表格视图

需要明显,因为用户可以购买许多项目。

select distinct(ipod.user_id )
from sales ipod
    inner join sales shoes on shoes.user_id = ipod.user_id 
    inner join sales bike on bike.user_id = ipod.user_id 
where ipod.item  = 'ipod' 
    and shoes.item = 'shoes'
    and bike.item = 'bicycle'

答案 1 :(得分:3)

此方法也可以轻松扩展到其他项目:

  select USER_ID, count(distinct ITEM)
    from SALES
   where ITEM in ('ipod', 'shoes', 'bicycle')
group by USER_ID
  having count(distinct ITEM) = 3

答案 2 :(得分:1)

最简单的解决方案是:

select user_id
from sales s1
where exists (select user_id from sales s2 
               where item = 'ipod' and s2.user_id = s1.user_id)
and exists (select user_id from sales s2 
               where item = 'shoes' and s2.user_id = s1.user_id)
and exists (select user_id from sales s2 
               where item = 'bycycle' and s2.user_id = s1.user_id)