本文介绍了mysql命令和groupby的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个MySQL日志表.它具有以下字段:id,status_id,object_id,已创建,已修改.
I got a MySQL table of logs. It has the following fields: id, status_id, object_id, created, modified.
我想知道获取每个对象的最新状态的最佳方法是什么?
I'm wondering what's the best way to get the latest status for each object?
提前谢谢!
我最后的解决办法是做
My last solution was to do
SELECT id, status_id, object_id, created, modified
FROM (SELECT * FROM logs ORDER BY created DESC) AS a
GROUP BY object_id
它可以工作,但是我认为有更好的方法可以做到这一点.有人在这里启发我们吗? :)
It works but I think there's a better way of doing this. Anyone care to enlighten us here at SO? :)
推荐答案
尝试一下,我没有检查过,但应该可以使用
try this, i've not checked this but should work
select object_id, status_id, MAX(created)
from ff
group by object_id having created = MAX(created)
关键是要使用having
功能,它将为每个分组的对象选择最后一个项目
the key is to use having
function which will choose last item for every grouped object
我添加了status_id
来选择;)
这篇关于mysql命令和groupby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!