![](/img/trans.png)
[英]How to sort morth and year values in the same field from mysql table using php
[英]How to sort year and month fields in same row from mysql table using php
我有一個帶有月和年字段的mysql表,如下所示。
year month filename filepath
2013 Feb 2013Feb_Report.xlsx ./main_reports/2013Feb_Report.xlsx
2013 Jan 2013Jan_Report.xlsx ./main_reports/2013Jan_Report.xlsx
2012 Jul 2012Jul_Report.xlsx ./main_reports/2012Jul_Report.xlsx
2013 Mar 2013Mar_Report.xlsx ./main_reports/2013Mar_Report.xlsx
2011 Mar monthly report180413.xlsx ./main_reports/monthly report180413.xlsx
2012 Sep 2012Sep_Report.xlsx ./main_reports/2012Sep_Report.xlsx
2012 Oct 2012Oct_Report.xlsx ./main_reports/2012Oct_Report.xlsx
我正在檢索此表中的所有字段,並將其打印如下。
2011 Mar : monthly report180413.xlsx
2012 Sep : 2012Sep_Report.xlsx
2012 Oct : 2012Oct_Report.xlsx
2013 Jan : 2013Jan_Report.xlsx
我想通過按DESC順序對月份和年份字段進行排序來檢索此表,如下所示。 我怎樣才能做到這一點? 我應該更改月份和年份字段的數據類型嗎? 請幫忙..
2013 Jan : 2013Jan_Report.xlsx
2012 Oct : 2012Oct_Report.xlsx
2012 Sep : 2012Sep_Report.xlsx
2011 Mar : monthly report180413.xlsx
我使用的SQL查詢如下。 它以DESC順序檢索年和月,但是月份以字母的DESC順序排序,即“ Jan”位於“ Feb”上方。 我需要的是“ Jan”上方的“ Feb”。
"SELECT * FROM main_reports ORDER BY year DESC, month DESC";
請任何幫助..預先感謝..
假設您正在使用MySQL。 嘗試使用方便的ORDER BY FIELD選項:
ORDER BY year DESC, FIELD( month, 'Dec', 'Nov', 'Oct', 'Sep', 'Aug', 'Jul', 'Jun', 'May', 'Apr', 'Mar', 'Feb', 'Jan' )
對於按月排序,我總是發現最好將它們存儲為整數值,然后通過PHP輸出文本版本
如果您當前將月份存儲為1月,2月,3月等,則無法正確訂購而不先轉換
例如,將數據庫中的所有月份轉換為Jan = 1,Feb = 2,Mar = 3等,那么您可以使用SQL順序
ORDER BY year DESC,month DESC
然后在您的PHP中,您可以輸出本月的文本版本
$monthName = date("F", mktime(0, 0, 0, $monthNumber));
echo $monthName;
如完全烘焙所指出的那樣,您正在嚴重濫用MySQL數據類型。 使用date或datetime列來處理與日期有關的數據,或者甚至更好地使用int(11)來存儲UNIX時間戳,以便於訂購/選擇日期范圍。
您可以輕松地編寫PHP / ASP腳本,以將當前表布局轉換為有效格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.