繁体   English   中英

Mysql 计算艺术家的歌曲总数

[英]Mysql count total songs for the artist

嗨,我需要 mysql 方面的帮助。

我有拖表艺术家song_artist现在我想为艺术家获取总歌曲。

**Artist** table
**id** | **artist_name**
1  | Artist Name1
2  | Artist Name2
3  | Artist Name3

**song_artist** table
id | song_id | artist_id
1 | 2 | 6
2 | 3 | 5
3 | 2 | 7
4 | 4 | 6
5 | 6 | 8

现在我想要这样的输出

Artist1 (2 songs)
Artist2 (1 songs)
Artist3 (5 songs)

现在我将其放入 2 个查询中,但我想使用一个查询来获取所有详细信息

这是我当前的代码。

$query = "select id, artist_name from artist order by artist_name";
$result=mysql_query($query);
while($row = mysql_fetch_array($result)){

  $query2 = "select COUNT(artist_id) as total_songs from song_artist WHERE artist_id = '".$row['id']."'";
  $result2=mysql_query($query2);
  echo $row['artist_name']." (".$row2['total_songs'].")<br>";
}

请帮我解决这个问题。

尝试

select concat(artist_name, '( ',  count(song_id), ' )') from artist 
       join song_artist on artist.id = song_artist.artist_id 
       group by artist.id, artist_name

如果您还想显示有 0 首歌曲的艺术家,则将查询中的join替换为left join

我不会在查询中连接字符串。 我会这样做:

$query = "SELECT ar.artist_name, COUNT(*) AS total_songs 
            FROM Artist ar
            JOIN song_artist sa ON sa.artist_id = ar.id
           GROUP BY ar.id";
$result=mysql_query($query);
while($row = mysql_fetch_array($result)){
    echo $row['artist_name']." (".$row['total_songs'].")<br>";
}
SELECT artist.id, artist.artist_name, COUNT(song_artist.artist_id) AS songs
FROM artist LEFT JOIN song_artist ON artist.id = song_artist.artist_id
GROUP BY artist.id, artist.artist_name ORDER BY artist.artist_name

注意:可能有更多性能替代品。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM