我有数据库:
电影(mID,标题,年份,导演):有一部电影的ID号为mID,标题,发行年份和导演。
审核人(rID,姓名):ID号为rID的审核人具有特定名称。
评分(rID,mID,stars,ratingDate):评论者rID在某个ratingDate上为电影mID提供了一些评级为(1-5)的星标。
我需要所有同一评论者对同一部电影进行过两次评分并且第二次给予更高评价的情况,并返回评论者的姓名和电影的标题。
我的查询
select r.name, m.title
from Reviewer r, Movie m, Rating rg
where rg.stars=(select max(g.stars) from Rating g
where rg.mID=g.mid and g.rID=rg.rID
group by g.stars
having count(g.mid)=2)
它没有给我带来任何结果 你能告诉我我的错误在哪里吗?
答案 0 :(得分:1)
Select r.name, m.title From Rating rg
Left join Reviewer r ON rg.rID = r.rID
Left join Movie m ON rg.mID = m.mID
Where rg.stars > (
Select Top 1 g.stars From Rating g
Where -- g.ratingDate != rg.ratingDate AND -- discard same rating
g.mID = rg.mID and g.rID = rg.rID
order by ratingDate desc
)
答案 1 :(得分:0)
试试这个:
SELECT r.name,
m.title
FROM ( SELECT rid,mid -- Here we get all rid and mid that have been reviewed twice
FROM rating
GROUP BY rid,mid
HAVING COUNT(stars) = 2
) AS m
INNER JOIN (SELECT distinct r1.rid, r1.mid --Here we get all rid and mid that
FROM rating r1 --was rated higher the second time
INNER JOIN rating r2
ON r1.rid = r2.rid AND
r1.mid=r2.mid AND
r1.ratingdate > r2.ratingdate AND
r1.stars > r2.stars
) AS c
ON c.rid = m.rid AND
c.mid=m.mid
LEFT JOIN Reviewer r
ON c.rid=r.rid
LEFT JOIN Movie m
ON m.mid=c.mid