简体   繁体   English

MySQL中的复杂SQL查询

[英]Complex SQL query in MySQL

I have the following tables in the database: 我的数据库中有以下表格:

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

Tables albums and songs relate to band_id from table bands by album_owner and song_owner . albumssongs涉及到band_id从表bandsalbum_ownersong_owner

Table ratings relates to song_id from table songs by rating_song . ratingssong_id的表songsrating_song

Given the tables above how can I get all the bands and the count of albums, song and rating for each one? 鉴于以上表格,我如何获得所有乐队以及每张专辑的数量,歌曲和评价? The ratings must be returned as the sum of rating_value divided by the number of rates. 评分必须以rating_value的总和除以评分数得出。

try this 尝试这个

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

To do it all in one query, you need to use subqueries. 要在一个查询中完成所有操作,您需要使用子查询。

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

I'm assuming here that you mean you want the average rating for all songs for each band. 我在这里假设您的意思是您想要每个乐队的所有歌曲的平均评级。 If you meant you want the average rating for each song, then it doesn't really make sense to do it as a single query, because the count of number of albums applies to a band, not to a song, though I suppose you could return one row per song with the number of albums for the band repeated on each song. 如果您想获得每首歌曲的平均评分,那么将其作为一个查询就没有任何意义,因为专辑数量是针对某个乐队而不是某首歌曲的,尽管我认为您可以每首歌曲返回一行,并在每首歌曲上重复该乐队的专辑数量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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