2011-07-12 70 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 

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

相关问题