如同这个问题:Retrieving the last record in each group,我想查询每个组的最新条目。
与链接问题不同,我还想为最长时间添加一个标准。
我尝试了以下内容:
SELECT m1.*
FROM messages m1
LEFT JOIN messages m2
ON (
m1.name = m2.name AND
m1.id < m2.id AND
m2.time <= nnnnnnn
)
WHERE m2.id IS NULL
AND m1.time <= nnnnnnn;
我不确定这是否100%正确,有更好的解决方案吗?也许没有重复的time <= nnnnnnn
条件?
答案 0 :(得分:0)
您可以在where
子句中执行此操作:
select m.*
from messages m
where m.id = (select m2.id
from messages m2
where m2.name = m.name and
m2.time <= nnnn
order by m2.time desc
limit 1
)
答案 1 :(得分:0)
这就是你要找的东西。最后正每组-低于X
SELECT m1.*
FROM messages m1
LEFT JOIN messages m2 ON (
m2.name = m1.name AND
IF(m2.date < 'nnnnnnn',m2.date > m1.date, m1.date > 'nnnnnnn'))
WHERE m2.idIS NULL