在sql中第二次选择最高值

eufgjt7s  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(356)

我正在做一个sql练习:对于同一个评审员对同一部电影进行了两次评分,第二次评分更高的所有情况,请返回评审员的姓名和电影的标题。
我的解决方案就在这里,它是有效的,但我认为这应该是一个更聪明的方式得到这个解决方案。经过几次检查后,我在代码末尾插入了条件“limit 1 offset 1”,因为我第一眼看到的结果就是我想要的结果。我的问题是,我认为我的方法不能自动执行查询。有什么改进我代码的建议吗?

SELECT name, title
 FROM Rating
 JOIN Reviewer 
 ON Reviewer.rID = Rating.rID
 JOIN Movie 
 ON Movie.mID = Rating.mID
 GROUP BY name
 ORDER BY ratingDate DESC 
 LIMIT 1 OFFSET 1;

我的新查询是:

SELECT
    name, title
FROM
     Rating
JOIN Reviewer ON Reviewer.rID = Rating.rID
JOIN Movie    ON Movie.mID = Rating.mID
     WHERE
         NOT EXISTS (SELECT *
            FROM Rating   later_higher
           WHERE later_higher.rid = Rating.rid
             AND later_higher.mid  = Rating.mid
             AND later_higher.stars > Rating.stars
             AND later_higher.ratingDate > Rating.ratingDate
         )
         AND EXISTS (SELECT *
            FROM Rating   earlier_lower
           WHERE earlier_lower.rid = Rating.rid
             AND earlier_lower.mid = Rating.mid
             AND earlier_lower.stars < Rating.stars
             AND earlier_lower.ratingDate < Rating.ratingDate
        )
velaa5lx

velaa5lx1#

SELECT name, title FROM(SELECT name, title, ROW_NUMBER() OVER(PARTITION BY 
 re.reviewer_id, re.film_id ORDER BY re.score DESC) seq
 FROM Rating ra
 LEFT JOIN Reviewer re ON ra.rID = re.rID
 LEFT JOIN Movie m ON ra.mID = m.mID
) a WHERE a.seq = 1;

这将根据评论员和电影对评论进行划分,然后根据最高的评分对评分进行排序。所以一个评审员可以评审多部电影,但他/她评审的每部电影需要最高的分数。

krcsximq

krcsximq2#

如果。。。
有一个较低的分数较早的审查
没有更高分数的后续审查(后续审查将返回)
http://sqlfiddle.com/#!9/8fbff4/1号

SELECT
  *
FROM
  reviews
WHERE
  NOT EXISTS (SELECT *
                FROM reviews   later_higher
               WHERE later_higher.reviewer_id = reviews.reviewer_id
                 AND later_higher.film_id     = reviews.film_id
                 AND later_higher.score       > reviews.score
                 AND later_higher.review_date > reviews.review_date
             )
  AND EXISTS (SELECT *
                FROM reviews   earlier_lower
               WHERE earlier_lower.reviewer_id = reviews.reviewer_id
                 AND earlier_lower.film_id     = reviews.film_id
                 AND earlier_lower.score       < reviews.score
                 AND earlier_lower.review_date < reviews.review_date
             )

然后,您可以加入任何其他您喜欢的表,以获得电影名称,评论员姓名等。

相关问题