在SQL中第二次选择最高值

时间:2018-05-17 15:31:54

标签: mysql sql

我正在进行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
        )

2 个答案:

答案 0 :(得分:1)

如果......返回评论

  • 之前的评分较低
  • 以后没有更高分的评论(后来评论WOULD返回)

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
             )

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

答案 1 :(得分:-1)

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;

根据评论者和电影对评论进行分区,然后根据最高评分对评分进行排序。因此,评论者可以审阅多部电影,但每部电影需要得分最高,他/她进行了审核。