我正在使用 MySQL。
我想要的结果是显示“time”最高的行,其中“res”=“hans”,并对“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
最佳答案
有几种方法可以做到这一点。一种是使用子查询并连接
回到原始表:
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
子句中未在聚合中使用的字段(在我看来这是一个错误 - 大多数其他数据库不允许这种行为)。通过允许它,它只会返回一个随机结果,尽管这正是您所经历的。
这是使用外连接
的另一种方法,但我认为前一种方法更容易理解:
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
关于mysql - 按 max() 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35819991/