gpt4 book ai didi

mysql - 在 SQL 中第二次选择最大值

转载 作者:行者123 更新时间:2023-11-30 21:43:49 27 4
gpt4 key购买 nike

我正在做一个 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
)

最佳答案

这会返回评论,如果...

  • 有较早的评分较低的评论
  • 没有更高分的后来评论(以后的评论会返回)

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
)

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

关于mysql - 在 SQL 中第二次选择最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50395328/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com