【问题标题】:group by order by max()按 max() 顺序分组
【发布时间】:2016-06-19 14:26:02
【问题描述】:

我正在使用 MySQL。

我想要的结果是显示'res' = 'hans'的'time'最高的行,并将'frm'分组。

我正试图摆弄 GROUP BY、ORDER BY、MAX(time) - 我不会去哪里。

我的表:'消息'

| frm  | res  | time |   msg    | opnd |
| poul | hans | 0916 | hi there |   1  |
| john | hans | 1033 | waz up   |   1  |
| hans | john | 1140 | new text |   0  |
| poul | john | 1219 | message  |   0  |
| poul | hans | 1405 | respond  |   0  |
| john | hans | 1544 | write    |   0  |

我想要的结果:

poul - hans - 1405 - respond - 0
john - hans - 1544 - write   - 0

我得到的结果:

poul - hans - 1405 - hi there - 1
john - hans - 1544 - waz up   - 1

我得到的“时间”是正确的,但“msg”和“opnd”是错误的。

我的代码:

SELECT frm, res, MAX(time), msg, opnd
FROM messages
WHERE res = 'hans'
GROUP BY frm
ORDER BY time DESC

【问题讨论】:

    标签: mysql group-by max sql-order-by


    【解决方案1】:

    有几种方法可以做到这一点。一种是使用子查询和join回到原表:

    SELECT m.*
    FROM messages m 
       JOIN (
          SELECT frm, res, MAX(time) maxtime
          FROM messages
          WHERE res = 'hans'
          GROUP BY frm, res) m2 on m.frm = m2.frm 
                          and m.res = m2.res
                          and m.time = m2.maxtime
    ORDER BY m.time DESC
    

    Mysql 允许您省略 group by 子句中未在聚合中使用的字段(imo 错误——大多数其他数据库不允许这种行为)。通过允许它,它只会返回一个随机结果,尽管这就是您所遇到的。


    这是另一种使用outer join的方法,但我认为前者更容易理解:

    select m.*
    from messages m 
       left join messages m2 on m.frm = m2.frm
                           and m.res = m2.res
                           and m2.time > m.time
    where m2.frm is null 
       and m.res = 'hans'
    order by m.time desc
    

    【讨论】:

    • Thnx,这似乎工作。没想到会这么复杂。
    【解决方案2】:

    您的问题是您按一列分组,但您选择了几列。因此,对于其他未按列分组的结果,您只会得到其中一个结果,而不一定是属于 max(time) 值的结果。

    你需要这样的东西:

    select a.frm, a.res, b.max_time, a.msg, a.opnd from 
    messages as a inner join
    (SELECT frm, MAX(time) as max_time
    FROM messages
    WHERE res = 'hans'
    GROUP BY frm) on a.frm = b.frm and a.time = b.max_time
    ORDER BY time DESC
    

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 2010-10-06
      • 2021-12-17
      • 2013-09-13
      • 2011-06-08
      • 2019-04-05
      • 1970-01-01
      相关资源
      最近更新 更多