MySQL Months存储为字符串,如何按时间顺序排序,而不是按字母顺序排序?

时间:2011-12-16 18:55:20

标签: mysql

我已经将这些月份存储在像“12月,8月,7月”这样的表中,等等。我如何订购我的查询,以便按时间顺序而不是按字母顺序排序?我可能需要从字符串转换为时间来获取一个数字然后按顺序排序,我可以在PHP中执行此操作但不知道如何在查询中直接执行此操作,因此我不必进行查询,使用PHP操纵一些数据,然后使用它进行另一个查询。

MySQL可以在查询中执行此操作吗?

感谢。

6 个答案:

答案 0 :(得分:3)

我要做的是创建另一张表

CREATE TABLE MONTH_NAME
( 
    MONTH_NAME VARCHAR, // or whatever type the month is in your db
    MONTH_NUMBER INT
)

填写“1月”,1等

然后在查询中将这两个表加入月份名称并按MONTH_NUMBER排序。

答案 1 :(得分:1)

是的,你会讨厌这个: -

order by 
case month_column
  when "January" then 1
  when "February" then 2
  ...
  when "December" then 12
end case

mysql中还有另一个str_to_date函数

mysql> select str_to_date('January', '%M');
+------------------------------+
| str_to_date('January', '%M') |
+------------------------------+
| 0000-01-00                   |
+------------------------------+

--> sorting
order by str_to_date(column_name, '%M')

由于您不打算提供其他信息(年,日,时间), 所以这个功能也可以。

最好的方法是将所有字符串转换为小整数,
这是正确的方法,并有最好的优化

答案 2 :(得分:1)

您可以使用CASE statement

SELECT 
CASE 
    WHEN `month` = 'January' THEN 1
    WHEN `month` = 'February' THEN 2
    WHEN `month` = 'March' THEN 3
    WHEN `month` = 'April' THEN 4
    WHEN `month` = 'May' THEN 5
    ....
END AS orderbymonth
FROM yourtable
ORDER BY orderbymonth ASC

答案 3 :(得分:0)

如果您有months表,则可以按month_number订购。

select field from tablename join months using (month_name) 
  order by month_number asc;

e.g。

insert into months (month_name, month_number) 
  values ('January', 1), ('February', 2), ...

答案 4 :(得分:0)

我会在表db类型整数中添加一列。然后我将使用monthes创建另一个引用表Col1名称:January Col2值:1:Col1名称:February Col2值:2 ..等 然后我会内部加入名称,并按值排序。 100%工作

答案 5 :(得分:0)

试试这个:

SELECT * FROM tablename ORDER BY FIELD(month_column,
'December', 'November', 'October',
'September', 'August', 'July',
'June', 'May', 'April',
'March', 'February', 'January') DESC, month_column ASC

希望这会有所帮助。

相关问题