[英]Complex SQL query in MySQL
我的數據庫中有以下表格:
bands
- band_id
- band_name
albums
- album_id
- album_name
- album_owner
songs
- song_id
- song_name
- song_owner
ratings
- rating_id
- rating_value
- rating_song
表albums
和songs
涉及到band_id
從表bands
由album_owner
和song_owner
。
表ratings
與song_id
的表songs
的rating_song
。
鑒於以上表格,我如何獲得所有樂隊以及每張專輯的數量,歌曲和評價? 評分必須以rating_value的總和除以評分數得出。
嘗試這個
Select Band_Id, Band_Name,
(Select Count(*) From Albums
Where Album_Owner = B.Band_Id) AlbumCount,
S.Song_Id, S.Song_Name,
Avg(rating_value) Rating
From Bands B
Left Join Songs S
On S.Song_Owner = B.Band_Id
Left Join Ratings R
On R.rating_song = S.Song_Id
Group By Band_Id, Band_Name, S.Song_Id, S.Song_Name
要在一個查詢中完成所有操作,您需要使用子查詢。
select band_name,
(select count(*)
from album
where album_owner=band_id) as album_count,
(select count(*)
from song
where song_owner=band_id) as song_count,
(select avg(rating_value)
from song
join rating on rating_song=song_id
where song_owner=band_id) as average_rating
from band
我在這里假設您的意思是您想要每個樂隊的所有歌曲的平均評級。 如果您想獲得每首歌曲的平均評分,那么將其作為一個查詢就沒有任何意義,因為專輯數量是針對某個樂隊而不是某首歌曲的,盡管我認為您可以每首歌曲返回一行,並在每首歌曲上重復該樂隊的專輯數量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.