我需要帮助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 :(得分: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
答案 1 :(得分:1)
如果您还要显示包含0首歌曲的艺术家,请将查询中的join
替换为left 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>";
}
答案 2 :(得分: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
注意:可能有更多高性能的替代品。