SQL选择共享一列的更多行,并在另一列中包含少量值之一

时间:2018-04-16 19:08:29

标签: mysql sql select

假设我有这样的表:

+-----------------+-----------------+
| name            | playlist        |
+-----------------+-----------------+
| Jay-Z           | chill vibes     |
+-----------------+-----------------+
| Jay-Z           | rap             |
+-----------------+-----------------+
| Jay-Z           | discover weekly |
+-----------------+-----------------+
| Imagine Dragons | discover weekly |
+-----------------+-----------------+
| ZEDD            | discover weekly |
+-----------------+-----------------+
| Imagine Dragons | pop             |
+-----------------+-----------------+

我需要选择播放列表中的作者每周发现和RAP。我所知道的只是播放列表。如何用纯SQL做到这一点,甚至可能吗?

2 个答案:

答案 0 :(得分:2)

你可以使用过滤器让不同的播放列表的数量等于你正在寻找的数字

  select name  
  from my_table  
  where playlist in ('discover weekly', 'rap')
  group by name
  having count(distinct playlist) = 2

答案 1 :(得分:1)

使用分组和计数。见下文:

select name
from table1
where playlist in ('rap','discover weekly')
group by name
having count(distinct playlist) = 2;

Result:  Jay-Z