【问题标题】:How to get the highest and lowest result per ID passed in WHERE IN如何获得在 WHERE IN 中传递的每个 ID 的最高和最低结果
【发布时间】:2019-05-01 17:27:44
【问题描述】:

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

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

目前,我在应用中手动过滤 cmets。

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

【问题讨论】:

    标签: mysql


    【解决方案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) 
    

    如果有相同等级的cmets,将全部返回。

    【讨论】:

    • 嗯,看起来很有希望。将在几个小时内对其进行测试并回复您。非常感谢!
    【解决方案2】:
    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
    

    【讨论】:

    • OP 也需要相应的 cmets。此查询无法解决此问题
    猜你喜欢
    • 1970-01-01
    • 2011-03-05
    • 2010-09-13
    • 1970-01-01
    • 2019-04-24
    • 2020-03-25
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    相关资源
    最近更新 更多