繁体   English   中英

MySQL中的复杂SQL查询

[英]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

albumssongs涉及到band_id从表bandsalbum_ownersong_owner

ratingssong_id的表songsrating_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM