Mysql 查询:获取歌曲的作者并计算该作者的歌曲总数

Mysql 查询:获取歌曲的作者并计算该作者的歌曲总数,mysql,subquery,Mysql,Subquery,我不确定如何执行以下查询。我有三张桌子: song (song_id, title, is_draft) author (author_id, name) song_author (song_id, author_id, display_order) 有很多歌曲,一首歌可以有多个作者,一个作者可以写多首歌 我想输出一首特定歌曲的作者以及每个作者所写歌曲的总数 因此,如果我选择宋id:598,我想要这样的结果集 author_id name total songs he

我不确定如何执行以下查询。我有三张桌子:

song (song_id, title, is_draft)
author (author_id, name)
song_author (song_id, author_id, display_order)
有很多歌曲,一首歌可以有多个作者,一个作者可以写多首歌

我想输出一首特定歌曲的作者以及每个作者所写歌曲的总数

因此,如果我选择宋id:598,我想要这样的结果集

author_id    name           total songs he wrote
------------------------------------------------
234          Michael Lord   58
589          Lama Turc      12
注意:每个作者撰写的歌曲总数必须排除歌曲为歌曲的歌曲。is_draft等于1,并且顺序歌曲作者设置的结果。displayorder

根据我的研究,我想我必须做两个查询(子查询),但这是我所能做的


谢谢你,我也是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;
试试这个

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

这是一种较旧的语法——有些人对较新的显式连接语法了如指掌——但从形式上看,这种语法效果很好。谢谢——我想问一下,与A上的内部连接B相比,x=y和C上的内部连接B在性能上是否有什么真正的区别,其中y=z,但我确信我可以用谷歌搜索一下。有趣的是知道它是旧的。您在选择歌曲\u id吗?没有看到您想要的最后一次编辑是\u draft=1并按显示顺序排序。请查看更新的答案。尝试过,但我总是得到“总计”1…我知道还有更多您自己尝试过子查询吗?这给了您满意的结果吗?仍然得到1作为歌曲总数运行它而不带where子句,看看您在任何行上得到的计数是否高于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;