2013-07-03 35 views
0

我不知道如何执行以下查询。我有3个表:查询:获取歌曲的作者并统计该作者的歌曲总数

song (song_id, title, is_draft) 
author (author_id, name) 
song_author (song_id, author_id, display_order) 

有歌曲,一首歌曲可以有多个作者和作者可以写多首歌曲

我要输出特定歌曲的作者与歌曲总数每个作者写的。

所以,如果我挑song_id:,我希望能有一个结果集,这样

author_id name   total songs he wrote 
------------------------------------------------ 
234   Michael Lord 58 
589   Lama Turc  12 

注:每个作者写道必须排除歌曲的歌曲总数为song.is_draft等于1和顺序结果通过song_author.displayorder

设置

从我的研究,我认为我必须做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; 
+0

这是旧的语法 - 有些人却全部包裹起来的新的明确的JOIN语法 - 但FO RME,这个效果很好。 – Randy

+0

谢谢,我会问是否有任何真正的性能差异相比,A内部加入B在一个地方X = Y INNTER加入B在C如果Y = Z,但我敢肯定,我可以只是谷歌它。有趣的是知道它的年龄更大 – Acantud

+0

是你选择song_id吗? – Marco

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 
+0

没有看到您想要的最后编辑is_draft = 1并按显示顺序排序。请看更新的答案。 – AJP

+0

尝试过,但我总是得到一个'总'1 ...我知道还有更多 – Marco

+0

你有没有尝试过自己的子查询?是否给你满意的结果? – AJP

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;