获取mySQL MONTH()以使用前导零?


92

如何在此查询中指定mySQL的MONTH()函数返回'08'而不是8?

我想按日期进行排序。目前正在获得有关日期的结果,例如

2006-9
2007-1
2007-10
2007-11

当前查询:

SELECT COUNT(*), CONCAT(YEAR(`datetime_added`), '-', MONTH(`datetime_added`)) as date FROM `person` WHERE (email = '' OR email IS NULL) 
GROUP BY date 
ORDER BY date ASC

Answers:


207

请改用以下内容:

DATE_FORMAT(`datetime_added`,'%Y-%m')

说明:

DATE_FORMAT()函数可让您使用下表中说明的格式以任何方式格式化日期(从文档中逐字获取)。因此,格式字符串的'%Y-%m'意思是:“整年(4位数字),后接破折号(-),后跟两位数的月份数字”。

请注意,您可以通过设置lc_time_names系统变量来指定用于日/月名称的语言。非常有用。有关更多详细信息,请参考文档

Specifier   Description
%a  Abbreviated weekday name (Sun..Sat)
%b  Abbreviated month name (Jan..Dec)
%c  Month, numeric (0..12)
%D  Day of the month with English suffix (0th, 1st, 2nd, 3rd, …)
%d  Day of the month, numeric (00..31)
%e  Day of the month, numeric (0..31)
%f  Microseconds (000000..999999)
%H  Hour (00..23)
%h  Hour (01..12)
%I  Hour (01..12)
%i  Minutes, numeric (00..59)
%j  Day of year (001..366)
%k  Hour (0..23)
%l  Hour (1..12)
%M  Month name (January..December)
%m  Month, numeric (00..12)
%p  AM or PM
%r  Time, 12-hour (hh:mm:ss followed by AM or PM)
%S  Seconds (00..59)
%s  Seconds (00..59)
%T  Time, 24-hour (hh:mm:ss)
%U  Week (00..53), where Sunday is the first day of the week
%u  Week (00..53), where Monday is the first day of the week
%V  Week (01..53), where Sunday is the first day of the week; used with %X
%v  Week (01..53), where Monday is the first day of the week; used with %x
%W  Weekday name (Sunday..Saturday)
%w  Day of the week (0=Sunday..6=Saturday)
%X  Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V
%x  Year for the week, where Monday is the first day of the week, numeric, four digits; used with %v
%Y  Year, numeric, four digits
%y  Year, numeric (two digits)
%%  A literal “%” character
%x  x, for any x not listed above 

8
虽然不是他的要求,但这似乎可以回答他本应提出的要求。
Jeremy Holovacs,2011年

为什么月份中的某天为0?
SOFe

因为0000-00-00是有效日期(取决于设置)
Mchl

2
@SOFe>月和日说明符的范围以零开头,原因是MySQL允许存储不完整的日期,例如'2014-00-00'。dev.mysql.com/doc/refman/5.6/en/...
kio21

太棒了,像魅力一样工作:)
Mizo Games

32

您可以使用填充

SELECT
    COUNT(*), 
    CONCAT(YEAR(`datetime_added`), '-', LPAD(MONTH(`datetime_added`), 2, '0')) as date 
FROM `person` 
WHERE (email = '' OR email IS NULL) 
GROUP BY date 
ORDER BY date ASC

满足蜂巢中的需求。蜂巢中不支持DATE_FORMAT()函数。您的答案会有所帮助。


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.