mysql从表中选择distinct months(缩写)

时间:2014-01-04 10:06:26

标签: mysql sql distinct

我想看看我的桌子里用了几个月。我可以获得id和名字(见下文)没问题,但是我无法拔出abrv。我在使用%b之前已经完成了,但似乎无法在这里获得语法。我哪里错了?

    SELECT DISTINCT 
    MONTH(date) as id, 
    MONTHNAME(date) as name, 
    MONTHNAME(date, '%b') as abrv
    FROM table_name ORDER BY id ASC

我想返回

    id  |name       |abrv
    1   |January    |Jan

2 个答案:

答案 0 :(得分:3)

我愿意:

    SELECT DISTINCT 
    MONTH(date) as id, 
    MONTHNAME(date) as name, 
    SUBSTRING(MONTHNAME(date),1,3) as abrv
    FROM table_name ORDER BY id ASC

答案 1 :(得分:1)

使用date_format功能,而不是monthname
http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-format

   SELECT DISTINCT 
    MONTH(date) as id, 
    MONTHNAME(date) as name, 
    DATE_FORMAT(date, '%b') as abrv
    FROM table_name ORDER BY id ASC