按max()顺序分组

时间:2016-03-05 21:15:13

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

我正在使用MySQL。

我想要的结果是显示时间最长的行'在哪里' res' =' hans',并对' frm'进行分组。

我正在努力摆弄GROUP BY,ORDER BY,MAX(时间) - 而且我没有去哪里。

我的表格:'消息'

| 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

2 个答案:

答案 0 :(得分:2)

有几种方法可以做到这一点。一种是使用子查询并将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子句中未用于聚合的字段(错误即可 - 大多数其他数据库不允许此行为)。通过允许它,它只返回一个随机的结果,虽然这是你正在经历的。

此处'使用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

答案 1 :(得分:0)

您的问题是您按一列进行分组,但是您可以选择多列。因此,对于其他未分组的列,您将只获得其中一个结果,而不是nececarily属于最大(时间)值的结果。

你需要这样的东西:

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