如何排序年和月字段在同一行从mysql表使用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'之上。我需要的是"Feb"在"Jan"上面。

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

正如fullybaked指出的那样,你严重滥用MySQL数据类型。可以使用date或datetime列来处理与日期相关的数据,或者更好地使用int(11)来存储UNIX时间戳,以便于排序/日期范围的选择。

您可以很容易地编写一个PHP/ASP脚本来将当前的表布局转换为有效的格式。