问题
I am selecting the most recent entries of a MySQL table with:
SELECT MAX(time) as most_recent, userID
FROM TableName
GROUP BY userID
ORDER BY most_recent DESC
My problem is, if I want to limit the maximum time with:
WHERE time <= nnn
The query does not work anymore. Is there a solution for with without a subquery?
Thanks in advance!
回答1:
you can do it with subquery :
select t.userID, max(t.time)
from
(
select userID, time
from tableName
where time <= nnn
) t
group by t.userID
or simply :
select userID, max(time)
from tableName
where time <= nnn
group by userID
回答2:
Use the HAVING
clause like so:
SELECT MAX(time) as most_recent, userID
FROM TableName
GROUP BY userID
HAVING MAX(time) <= nnn
ORDER BY most_recent DESC
来源:https://stackoverflow.com/questions/13216762/selecting-most-recent-mysql-rows-by-maxtime-where-time-x