我有一个小型数据库,其中有四个表排列如下;
TABLE band_members COLUMNS:band_id(PK),name,dob,country,sex
TABLE band COLUMNS:band_id(PK),band_name
表cds COLUMNS:cd_id(PK),rdate,title,position,weeks
TABLE发布COLUMNS:cd_id,band_id
我要做的是显示乐队的名称以及他们拥有头号记录的次数。 (即位置=' 1')
这是我尝试的代码似乎无法正常工作:
SELECT band_name
FROM cds
JOIN releases ON cds.cd_id = releases.cd_id
JOIN bands ON releases.band_id = bands.band_id
GROUP BY (position='1')
答案 0 :(得分:0)
你应该有一个bandmembers_band表,因为你最有可能最终必须处理属于多个乐队的乐队成员 - 这种情况经常发生在这些日子里。
回答:
SELECT band_name, count(cds.cd_id)
FROM (select cds.cd_id, cds.position from cds where cds.position = 1 group by cds.cd_id)
JOIN releases ON cds.cd_id = releases.cd_id
JOIN bands ON releases.band_id = bands.band_id
GROUP BY band_name
having count(cds.cd_id) > 0
(伪 - 可以开箱即用)