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

时间:2011-04-11 13:13:02

标签: php mysql database

我在编写MySQL查询时遇到问题。 我在DB

中有以下字段
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

请帮帮我......

提前致谢.....

4 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:4)

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

答案 2 :(得分:2)

您首先需要按年份分组(否则您将在其他年份过滤掉几个月)。使用MAX()获得每个组的最大日期。

SELECT *, MAX(created_on) FROM table
GROUP BY YEAR(created_on), MONTH(created_on) 

答案 3 :(得分:2)

假设当天只有一条记录;

SELECT * from table where created_on IN (Select MAX(created_on) FROM table
GROUP BY YEAR(created_on), MONTH(created_on) )