簡體   English   中英

Mysql 計算藝術家的歌曲總數

[英]Mysql count total songs for the artist

嗨,我需要 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>";
}

請幫我解決這個問題。

嘗試

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 首歌曲的藝術家,則將查詢中的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>";
}
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

注意:可能有更多性能替代品。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM