Selecting most recent MySQL rows by MAX(time) WHERE time <= x

戏子无情 提交于 2019-12-12 14:43:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!