![](/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.