[英]Mysql count total songs for the artist
Hi i need help with mysql.嗨,我需要 mysql 方面的帮助。
I have tow table artist and song_artist now i want to get the total song for the artist.我有拖表艺术家和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
Now i want the out put like this现在我想要这样的输出
Artist1 (2 songs)
Artist2 (1 songs)
Artist3 (5 songs)
Now I'm getting this out put in 2 query but i want to use one query to get all the details现在我将其放入 2 个查询中,但我想使用一个查询来获取所有详细信息
This is my current code.这是我当前的代码。
$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>";
}
Please help me to solve this problem.请帮我解决这个问题。
Try尝试
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
if you want to also display artists with 0 songs then replace join
in query with left join
如果您还想显示有 0 首歌曲的艺术家,则将查询中的
join
替换为left join
I would not concatenate the string in query.我不会在查询中连接字符串。 this is how i would do it:
我会这样做:
$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
Note: There may be more performant alternatives.注意:可能有更多性能替代品。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.