在MySQL中获取每个月的最后一条记录....?

2022-08-30 23:32:51

我在为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 monthmonth FEB record # 3month MARCH record # 6month APRIL record # 8

请帮帮我.....

提前致谢.....


答案 1
SELECT * FROM table 
WHERE created_on in 
(select DISTINCT max(created_on) from table 
GROUP BY YEAR(created_on), MONTH(created_on))

答案 2

根据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 上有索引,否则,如果该表的行数超过几百行,则此查询将终止数据库。


推荐