如何获得在WHERE IN中传递的每个ID的最高和最低结果

时间:2019-05-01 17:27:45

标签: mysql

我正在使用ORM,我需要获取帖子以及其评分最高和最低的评论。 ORM执行下一个查询,以获取我查询的帖子的所有评论:

select * 
from `comments` 
where `comments`.`post_id` in (1, 2, 3, 4) 
order by `rating` desc

当前,我在应用中手动过滤评论。

如何更改此查询以使每个帖子仅返回2条评论-帖子的最高评分(MAX(rating))和最低评分(MIN(rating))评论?每个帖子至少有2条评论。

2 个答案:

答案 0 :(得分:1)

首先使用group by获取每个评论的最低和最高评分,然后加入表格:

select c.*
  from comments c inner join ( 
  select post_id, min(rating) minrating, max(rating) maxrating
  from comments
  group by post_id
) g on g.post_id = c.post_id and c.rating in (g.minrating, g.maxrating) 

如果有评论的评分相同,则会全部退回。

答案 1 :(得分:0)

SELECT post_id,MAX(rating) as highest_rated, MIN(rating) AS lowest_rated
FROM comments
WHERE post_id IN (1,2,3,4)
GROUP BY post_id