如何使用mysqli在查询中获取月份名称?

时间:2016-07-24 08:00:09

标签: php mysql mysqli

我正在尝试按月添加记录数。以下查询工作正常

SELECT    COUNT(*) AS count_by_month, MONTH(date_added) AS in_month
FROM      `promotion` 
WHERE     YEAR(date_added) = '2016' 
GROUP BY  MONTH(date_added)

但是上面的查询是在结果中返回月份数字,我希望得到月份名称,如JanFeb而不是数字。我尝试了以下技巧,但它没有用。

    SELECT    COUNT(*) AS count_by_month, 
    MONTH(date_added) AS in_month, MONTHNAME(STR_TO_DATE(in_month, '%m'));
    FROM      `ws_promotion` 
    WHERE     YEAR(date_added) = '2016' 
    GROUP BY  MONTH(date_added)

任何人都可以指导我如何解决这个问题,如果有人指导我,我会很感激。谢谢。

1 个答案:

答案 0 :(得分:2)

试试这个:

SELECT    
    COUNT(*) AS count_by_month, 
    MONTH(date_added) AS in_month, 
    MONTHNAME(date_added)
FROM      `ws_promotion` 
WHERE     YEAR(date_added) = '2016' 
GROUP BY  MONTH(date_added)

注意: MONTHNAME(date)函数需要date作为参数。

示例:

mysql> SELECT MONTHNAME('2009-05-18');
+-------------------------+
| MONTHNAME('2009-05-18') |
+-------------------------+
| May                     | 
+-------------------------+
1 row in set (0.02 sec)

更多: 如果您想从数字中获取月份名称,则可以使用STR_TO_DATE()将数字转换为日期,然后返回MONTHNAME()

SELECT MONTHNAME(STR_TO_DATE(7, '%m'));

+---------------------------------+
| MONTHNAME(STR_TO_DATE(7, '%m')) |
+---------------------------------+
| July                            |
+---------------------------------+