【问题标题】:Consider average rating as Zero in case that Roll No is not in the Rating List in MySQL如果 Roll No 不在 MySQL 的评级列表中,则将平均评级视为零
【发布时间】:2021-05-13 06:08:58
【问题描述】:

考虑以下架构:

Student (RollNo int Not Null, Name varchar(20) Not Null, YearOfAdmission int Not Null,
PRIMARY KEY(RollNo))
Friend(OwnRoll int Not Null, FriendRoll int Not Null,
PRIMARY KEY(OwnRoll, FriendRoll),
FOREIGN KEY fk_std1(OwnRoll) REFERENCES Student(RollNo),
FOREIGN KEY fk_std2(FriendRoll) REFERENCES Student(RollNo))
Movie(MID int Not Null, Title varchar(30) Not Null, YearOfRelease int Not Null, DirectorName
varchar(20) Null,
PRIMARY KEY(MID)) [Assume all director names are unique. However, same director can direct
many movies]
Rating(RollNo int Not Null, MID int Not Null, RatingDate date Not Null, Rating int Not Null,
PRIMARY KEY(RollNo, MID, RatingDate),
FOREIGN KEY fk_std4(RollNo) REFERENCES Student(RollNo),
FOREIGN KEY fk_mov2(MID) REFERENCES Movie(MID));

现在问题如下:

列出对所有电影的平均评分(包括多个评分实例)的学生 不同日期的电影)低于他/她的朋友对这些电影的平均评分 (包括在不同日期对电影进行评级的多个实例)。 (输出格式:RollNo1, AverageRating1、RollNo2、AverageRating2)

一个可能的答案是-

Select x.OwnRoll as RollNo1, l1.average as AverageRating1,
x.FriendRoll as RollNo2, l2.average as AverageRating2
from 
(
Select * from Friend 
union 
(
Select f.FriendRoll, f.OwnRoll from Friend as f
)
order by OwnRoll
) as x,

(
Select r.Rollno, avg(r.Rating) as average
from Rating as r 
group by r.Rollno
) as l1,

(
Select r.Rollno, avg(r.Rating) as average
from Rating as r 
group by r.Rollno
) as l2
where l1.Rollno = x.OwnRoll and l2.Rollno = x.FriendRoll
and l1.average > l2.average ;

但是这个版本没有考虑到没有给电影评分的朋友,所以他们的平均评分是0

提前感谢您对问题及其答案的任何更新。

【问题讨论】:

  • 添加这个问题的动机是为了得到一个比我刚刚在下面发布的更好、更简单的解决方案

标签: mysql join average


【解决方案1】:

如果没有 Roll No,请执行此小更新以将评分平均值捕获为 0。

Select distinct r.Rollno, avg(r.Rating) as average
from Rating as r 
group by r.Rollno
union
(
Select RollNo, 0 as average
from Student 
where Rollno not in (Select RollNo from Rating)
)

您甚至可以关注 Coalesce 更多关于提到的 here

类似问题已发布here

最终答案是

Select x.OwnRoll as RollNo1, l1.average as AverageRating1,
x.FriendRoll as RollNo2, l2.average as AverageRating2
from 
(
Select * from Friend 
union (Select f.FriendRoll, f.OwnRoll from Friend as f)
order by OwnRoll
) as x,

(
Select distinct r.Rollno, avg(r.Rating) as average
from Rating as r 
group by r.Rollno
union
(
Select RollNo, 0 as average
from Student 
where Rollno not in 
(Select RollNo from Rating))
) as l1,

(
Select distinct r.Rollno, avg(r.Rating) as average
from Rating as r 
group by r.Rollno
union
(
Select RollNo, 0 as average
from Student 
where Rollno not in 
(Select RollNo from Rating))
) as l2

where l1.Rollno = x.OwnRoll and l2.Rollno = x.FriendRoll
and l1.average > l2.average 

尝试逐步理解它!否则你会迷路的:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-27
    • 2016-02-13
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    • 2023-01-20
    相关资源
    最近更新 更多