mysql命令和分组依据

时间:2010-07-22 07:57:07

标签: sql mysql

我有一张MySQL日志表。它包含以下字段:id,status_id,object_id,created,modified。

我想知道获取每个对象的最新状态的最佳方法是什么?

提前致谢!

编辑: 我的最后一个解决方案是

SELECT id, status_id, object_id, created, modified 
FROM (SELECT * FROM logs ORDER BY created DESC) AS a
GROUP BY object_id

它有效,但我认为有更好的方法。有人关心在这里启发我们吗? :)

2 个答案:

答案 0 :(得分:2)

试试这个,我没有检查过这个但是应该可以工作

select object_id, status_id, MAX(created)
from ff
group by object_id having created = MAX(created)

关键是使用having函数,它将为每个分组对象选择最后一项

编辑:

我添加了status_id来选择;)

答案 1 :(得分:1)

你可能正在寻找

SELECT status_id FROM logs WHERE object_id = xx ORDER BY modified DESC LIMIT 0, 1

如果您有另一个包含状态代码的表,则可以使用

SELECT status_code FROM logs, status_codes_table
WHERE status_code_id = status_id AND object_id = xx
ORDER BY modified DESC LIMIT 0, 1

修改

如果您想拥有所有对象及其最新状态代码的表格,可以使用:

SELECT object_id, status_id
FROM logs
GROUP BY object_id
HAVING modified = MAX(modified)