簡體   English   中英

如何從mysql到php排序月份

[英]How to sort month years from mysql to php

我有一個來自mysql db的列表,其中包括月份和需要相應排序的年份。 目前,返回的列表(排序為DESC)如下所示:

122015 - (Dec 2015)
112015 - (Nov 2015)
102015 - (Oct 2015)
92015 - (Sep 2015)
82015 - (Aug 2015)
12016 - (Jan 2016)

我希望上面的列表遵循邏輯排序,其中2016年1月位於列表的頂部,例如

12016 - (Jan 2016)
122015 - (Dec 2015)
112015 - (Nov 2015)
102015 - (Oct 2015)
92015 - (Sep 2015)
82015 - (Aug 2015)

我該如何在php中實現呢?

*更新我使用的SQL查詢是:

SELECT mnthyears FROM dates ORDER BY mnthyears DESC

在ORDER BY子句中將mysql LPAD(填充函數)與SUBSTR方法結合使用:

SELECT mnthyears
FROM dates
ORDER BY SUBSTR(LPAD( mnthyears, 19, '0'),3,4) DESC, SUBSTR(LPAD(mnthyears,19,'0'),1,2) DESC

但是,如果只有5或6位數字的字符串(不帶“ - (Dec 2015) ”)),只需將19更改為6

使用MySQL str_to_date

str_to_date(replace(replace('(Jan 2016)',')',''),'(',''),'%b  %Y')

詢問

SELECT mnthyears FROM dates 
ORDER BY str_to_date(replace(replace('(Jan 2016)',')',''),'(',''),'%b  %Y') DESC

考慮到日期字符串更改的長度 ,您應該可以在SQL代碼中實現此目的-以后無需在PHP中完成此操作

select case when len(mnthyears ) = 18 then '0'+mnthyears else date_column end 
   as mnthyears FROM dates ORDER BY 1 DESC;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM