简体   繁体   中英

Mysql count total songs 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

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>";
}
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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