Need to pull last x number of rows based on date

孤人 提交于 2019-12-08 05:13:58

问题


I have a table with dates in "Aug 23, 2009" format and 5 values, so that it looks like this

SELECT * FROM table;
Date         | Total | V1 | V2 | V3 | V4   
Aug 21, 2009 | 41    | 23 | 8  | 8  | 2
Aug 22, 2009 | 39    | 22 | 8  | 7  | 2
Aug 23, 2009 | 35    | 20 | 6  | 7  | 2
Aug 24, 2009 | 34    | 20 | 6  | 6  | 2
Aug 25, 2009 | 32    | 19 | 5  | 6  | 2
Aug 26, 2009 | 31    | 19 | 5  | 5  | 2
Aug 27, 2009 | 30    | 19 | 5  | 5  | 1

So I need a query that will give me only the most recent (bottom) 3 entries. Should I setup some query by the date or just set a limit to the last 3 rows? I tried doing a subquery with a limit, but my version of MySQL does not support LIMIT in subquery, and to my knowledge there is no way to do a negative limit to grab the last x number of rows.


回答1:


select *
from table 
order by Date desc
limit 0, 3



回答2:


Can MySQl do TOP ? If so

   Select Top 3 * From Table
   Order By Date Desc



回答3:


Just change the order by to do your LIMIT.

So, in other words, add

ORDER BY `date` DESC 

to your select statement. You'll then be a ble to limit the return results to whatever row count you need.




回答4:


You don't need a sub-query, just use a LIMIT clause in your SELECT statement, and add an ORDER BY 'date' DESC clause. Generally it is a bad idea to use column names such as 'DATE' (or 'DATETIME' for that matter) because different databases may use these as reserved words.



来源:https://stackoverflow.com/questions/1343067/need-to-pull-last-x-number-of-rows-based-on-date

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