获取MySQL中每个月的最后一个记录....?
我在写MySQL查询时遇到了问题。 我在DB获取MySQL中每个月的最后一个记录....?
id created_on status
1 2011-02-15 12:47:09 1
2 2011-02-24 12:47:09 1
3 2011-02-29 12:47:09 1
4 2011-03-11 12:47:09 1
5 2011-03-15 12:47:09 1
6 2011-03-22 12:47:09 1
7 2011-04-10 12:47:09 1
8 2011-04-11 12:47:09 1
以下字段我需要select the last record of each month
。 这对于month FEB record # 3
month MARCH record # 6
和month APRIL record # 8
请帮我.....
在此先感谢.....
建立关Dheer的回答是:
SELECT r.*
FROM table AS r
JOIN (
SELECT MAX(t.created_on) AS created_on
FROM table AS t
GROUP BY YEAR(t.created_on), MONTH(t.created_on)
) AS x USING (created_on)
确保您有created_on索引,否则该查询,如果该表变得比几百行更杀了你的数据库。
子查询需要超过10分钟的时间...我有约。每天28条目..加入查询有很大的改进..谢谢它的大桌子工作.. – 2012-09-18 07:29:21
有什么办法可以将USING换成ON吗?我使用的框架似乎只使用ON,但我得到了不同的结果 – 2015-12-04 14:57:02
@RobertWent是:http://stackoverflow.com/a/11367066/175303 USING()只是ON()的缩写,所以前者总是可以扩展到后者。 – Zimzat 2015-12-06 18:48:58
首先,您需要按年和个月(否则你会在其他年份过滤掉几个月)。使用MAX()获取每个组的最大日期。
SELECT *, MAX(created_on) FROM table
GROUP BY YEAR(created_on), MONTH(created_on)
SELECT * FROM table
WHERE created_on in
(select DISTINCT max(created_on) from table
GROUP BY YEAR(created_on), MONTH(created_on))
谢谢reggie,它的工作..... – Pushpendra 2011-04-11 14:25:32
这应该被重写,把子查询放入一个JOIN,否则这会破坏数据库的表现:http://www.mysqlperformanceblog.com/ 2010/10/25/mysql-limitations-part-3-subqueries/ – Zimzat 2011-04-11 14:34:50
@Zimzat示例代码请 – user2636556 2016-07-22 13:22:18
假设有一天只有一条记录;
SELECT * from table where created_on IN (Select MAX(created_on) FROM table
GROUP BY YEAR(created_on), MONTH(created_on))
[我可以在mysql中使用聚合函数(LAST)吗?](http://stackoverflow.com/questions/5495913/can-i-use-aggregation-function-last-in-mysql) – 2011-04-11 13:23:24
检查我发布的答案。我相信它会回答你的问题。 – reggie 2011-04-11 13:38:14
查看http://stackoverflow.com/questions/1379565/mysql-first-and-last-record-of-a-grouped-record-aggregate-functions中接受的答案以获得更高效的解决方案 – eyaler 2012-06-25 12:45:49