MySQL将月份编号转换为月份名称
问题描述:
在MySQL中是否可以将整数/列转换为月份名称? 例如,1变为"Jan"或"January". 13及更高版本给出错误,否则将永远不会使用.
Is it possible to convert an integer/column to month name in MySQL? For example, 1 becomes 'Jan' or 'January'. 13 and onwards give an error, or will be never used.
答
- 我们可以使用
- We can convert the given input number to MySQL date format (focusing on month only), using
Str_To_Date()
function. - Now, we simply need to use
Monthname()
function to extract the month name from the date. - This will work only when
NO_ZERO_DATE
mode is disabled.
尝试:
SET sql_mode = ''; -- disable NO_ZERO_DATE mode SELECT MONTHNAME(STR_TO_DATE(1, '%m'));
按照注释中的 @Felk 的建议,如果我们需要缩短月份名称,可以使用
As @Felk suggested in comments, if we need to get shortened month name, we can use
Date_Format()
function instead:SET sql_mode = ''; -- disable NO_ZERO_DATE mode SELECT DATE_FORMAT(STR_TO_DATE(1, '%m'), '%b');
如果您不想禁用
NO_ZERO_DATE
模式,则可以使用月份创建任意随机日期,然后调用Monthname()
:
If you don't want to disable the
NO_ZERO_DATE
mode, then you can create any random date using the month and callMonthname()
:SELECT MONTHNAME(CONCAT('2018-',3,'-1')); -- 3 is the input number
- We can convert the given input number to MySQL date format (focusing on month only), using