2017-04-06 71 views
0

我處理下面的代碼:如何按月正確排序sql查詢結果?

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 

結果是這樣的:

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 
------------------------------------------------------------------- 

所有罰款eccept日期順序。正如你在第二排看到的那樣,它是1,12,2,3等等......雖然它應該是1,2,3,4等。 它是以字符串而不是數字排序的。

如何解決?

回答

0

已經找到了答案:我可以在第一行更改爲此進行排序:

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