0

As in this question: Retrieving the last record in each group, I want to query the latest entries of each group.

In difference to the linked question, I also want to add a criteria for the maximum time.

I have tried the following:

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;

I am not sure if this is 100% correct, Is there a better solution? Maybe without the duplicate time <= nnnnnnn condition?

Community
  • 1
  • 1
mario.schlipf
  • 1,257
  • 2
  • 13
  • 29

2 Answers2

0

You can do this in the where clause instead:

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
             ) 
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

This is what you're looking for. last-n-per-group-less-than-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
Parley Hammon
  • 27
  • 1
  • 3