开发者

Mysql count total songs for the artist

开发者 https://www.devze.com 2023-03-19 14:48 出处:网络
Hi i need help with mysql. I have tow table artist and song_artist now i want to get the total song for the artist.

Hi i need help with mysql.

I have tow table artist and song_artist now i want to get the total song for the 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

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


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.


if you want to also display artists with 0 songs then replace join in query with 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>";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消