2011-07-12 124 views
1

嗨,我需要幫助與MySQL。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>"; 
} 

請幫我解決這個問題。

+0

我剛剛注意到沒有一個來自song_artist的artist_ids在Artist表格的ID中! – RolandoMySQLDBA

回答

2

嘗試

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

這是正確答案bud –

+0

按id進行分組的目的是什麼(順便說一句,在這個查詢中是不明確的 - 'artist.id'或'song_artist.id')? –

+1

在mysql中,你不能通過'+'連接蜇蜇 –

1

,如果你想也顯示與0首歌曲的藝術家,然後用left join

取代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>"; 
} 
1
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 

注:可能有更好的性能的替代品。

相關問題