How to correctly order sql query results by month?

时间:2017-04-06 17:11:31

标签: mysql sql datetime

I'm dealing with the code below:

SELECT tbl.y YEAR, group_concat(month_posts SEPARATOR '-') dates
    FROM (
        SELECT YEAR(p.post_date) y, MONTH(p.post_date) m, concat(MONTH(p.post_date), ':', group_concat(p.id ORDER BY p.post_date ASC)) month_posts
        FROM prt_posts p    
        WHERE (p.post_status = 'publish' OR p.post_status = 'future') 
            AND p.post_type = 'event'
            AND p.post_date <= DATE('2016-12-31 00:00:00')
        GROUP BY y, m
        ORDER BY y, m ASC
     ) tbl
GROUP BY tbl.y
ORDER BY tbl.y DESC

The result is this:

year | dates
-------------------------------------------------------------------
2016     | 11:121,122-12:117,118
-------------------------------------------------------------------
2015     | 1:128-12:138-2:139-3:129-4:130-5:131-6:132-7:133-8:119-9:134
-------------------------------------------------------------------

All fine eccept the dates order. As you can see on the second row, it's 1, 12, 2, 3, etc... While it should be 1, 2, 3, 4, etc.. It's ordering as a string instead of number.

How to solve?

1 个答案:

答案 0 :(得分:0)

Already found the answer: I can sort by changing the first row to this:

SELECT tbl.y YEAR, group_concat(month_posts **ORDER BY tbl.m DESC** SEPARATOR '-') dates