来自现有列表的SQL查询

时间:2012-10-19 15:38:45

标签: sql

Sql newb所以我试图解决这个问题:

我提取购买某个项目的客户名单:

select r.name
from records r
where r.item_purchased='apple'

现在我想获取客户列表并提取他们购买的所有内容的记录,但我无法解决错误。我尝试过这样的事情:

with customer_list as
(above)
select r.*
from records r
where r.name=customer_list

3 个答案:

答案 0 :(得分:2)

我相信自我加入可以解决你的问题:

select distinct r2.*
from records r
join records r2
    on r2.name = r.name
where r.item_purchased='apple'

编辑:根据@ a_horse_with_no_name对结果之间差异的洞察力添加了DISTINCT,因为我怀疑自联接造成的重复是理想的结果。

答案 1 :(得分:2)

如果您确实想要使用CTE,这应该有效:

with customer_list as
(
  select r.name
  from records r
  where r.item_purchased='apple'
)
select r.*
from records r
where r.name in (select name from customer_list)

这与JOIN(例如Michael的解决方案)之间的区别在于,如果同一个客户多次购买苹果,则联接会产生不同的结果。

答案 2 :(得分:1)

Select * from records where name in (
                       select name
                         from records 
                        where item_purchased='apple'
)