选择按某些属性的行分组

时间:2019-01-11 13:15:15

标签: mysql sql

我有一个
艺术家表id, name
乐队表id, name, genre
乐队艺术家表artistid, bandid
我想查询所有不在摇滚乐队中演出的艺术家(一个艺术家可以在多个乐队中演奏。
以下查询有效:

SELECT  a.name  
FROM     arIst  a
WHERE   NOT EXISTS
(SELECT  *  
     FROM    arIst  a,  bandMembers bm, band    b   
     WHERE      a.id    =   bm.arIstID  
         AND    bm.id   =   b.id
         AND    b.genre =   “rock");    

但是我正在尝试通过分组依据来实现:

select a.name
from artists a, band b, band-artist ba
where a.id=ba.artistid and b.id=ba.bandid
group by(a.id)
HAVING ??? <--- here I am stuck

如何仅按组显示组中的所有行均遵循特定规则?
这里是band.genre != 'rock'

1 个答案:

答案 0 :(得分:2)

首先,您需要一个left join,因为有些歌手可能不在任何乐队中。其次,从不from子句中使用逗号。 始终使用正确的,明确的,标准 join语法。

select a.id, a.name  -- in case two artists have the same name
from artists a left join
     band_artist ba
     on a.id = ba.artistid left join
     band b
     on b.id = ba.bandid
group by a.id, a.name
having sum(band.genre = 'rock') = 0;  -- the number of rock bands is 0