一个简单的SQL查询问题

时间:2010-09-20 19:11:07

标签: sql

假设我有一个这样的表:

表1:

name     favorite_music
 a         country
 b         rock
 a         jazz
 b         jazz

如何进行此查询:找到favorite_music风格 “jazz”的名称。对于上面的例子,它应该只是“a”。

5 个答案:

答案 0 :(得分:8)

这应该得到他们:

select name
from table1
where favorite_music = 'country'
intersect
select name
from table1
where favorite_music = 'jazz'

编辑:问题不是很清楚。上面的查询将返回每个名称,其中爵士乐和国家/地区都是最喜欢的音乐风格(在您的示例表格中,名称='a')

编辑2 :只是为了好玩,一个例子应该使用子查询进行一次扫描:

select name from (
    select 
    name, 
    count(case when favorite_music = 'country' then 1 end) as likes_country,
    count(case when favorite_music = 'jazz' then 1 end) as likes_jazz,
    from table1
    where favorite_music in ('country', 'jazz')
    group by name
) where likes_country > 0 and likes_jazz > 0

答案 1 :(得分:8)

SELECT t1.name  
FROM table1 as t1  
INNER JOIN table1 AS t2 ON t1.name = t2.name 
WHERE t1.favorite_music = 'jazz' AND t2.favorite_music = 'country'  

答案 2 :(得分:1)

这将返回所有至少国家/地区和爵士乐最喜欢的音乐的名称:

select name from table1 where
  favorite_music in ('country', 'jazz')
group by name having count(name) = 2

这将返回所有完全(不是更多)国家/地区和爵士乐作为喜爱音乐的名称:

select name from table1 t1 where
not exists (
  select * from table1 t2 where
    t1.name = t2.name and
    t2.favorite_music not in ('country', 'jazz')
)
group by name having count(name) = 2

双重否定可能很棘手。您可以这样阅读:选择的所有人不是国家或爵士乐的音乐。这意味着他们喜欢乡村或爵士音乐。 group byhaving count = 2只关注他们喜欢的国家爵士乐。

答案 3 :(得分:0)

试试这个 - >

select x.name from table1 x, table1 y
where
x.name = y.name and
x.favorite_music = 'country' and 
y.favorite_music = 'jazz'

答案 4 :(得分:0)

pl / sql查询

选择名称 来自table1 favorite_music ='country' 要么 favorite_music ='爵士乐' 按名称分组 有COUNT(名字)> 1

OR

从中选择名称 (从table1中选择名称,favorite_music favorite_music ='country' 要么 favorite_music ='爵士乐' 按名称分组,favorite_music) 按名称分组  有COUNT(*)> 1