我不确定如何进行以下查询。我有3张桌子:
song (song_id, title, is_draft)
author (author_id, name)
song_author (song_id, author_id, display_order)
有歌曲,一首歌可以有多位作者,作者可以写多首歌
我想输出一首特定歌曲的作者,其中包含每位作者所写歌曲的总数。
所以,如果我选择 song_id : 598 ,我想要一个像这样的结果集
author_id name total songs he wrote
------------------------------------------------
234 Michael Lord 58
589 Lama Turc 12
注意:每位作者写的歌曲总数必须排除歌曲 song.is_draft 等于1且顺序结果设置 song_author.displayorder
从我的研究中,我认为我必须做2个查询(子查询),但这就是我得到的......
由于
答案 0 :(得分:1)
SELECT author.author_id, author.name, count(song.song_id)
FROM song, author, song_author,
WHERE song.song_id = $id
AND song.song_id = song_author.song_id
AND song_author.author_id = author.author_id
AND song_author.display_order != 1
GROUP BY song_author.author_id, author.name
ORDER BY author.author_id asc;
答案 1 :(得分:0)
试试这个..
select b.author_Id, b.name, COUNT(a.Song_Id) as 'total'
FROm song_author as a
INNER JOIN author as b
ON a.author_id = b.author_id
where a.song_id IN (select s.song_id
From songs as s
Where s.Song_Id = 598
AnD s.is_draft = 1)
GROUP bY b.author_Id, b.name
答案 2 :(得分:-1)
SQL也是新手,但是我可能会这么做?这没有明确说明连接,但我发现它适用于我的目的。如果这是不好的做法,也许有人可以告诉我?
Select author.author_id
, author.name
, count(author.author_id)
from song, author, song_author
where song.song_id = song_author.song_id
and author.author_id = song_author.author_id
group by author.authorid, author.name
order by author.author_id asc;