在单个查询中选择不同的年份和月份

时间:2012-08-22 12:08:58

标签: php mysql

如何在时间戳列中的单个查询中选择这些年份的不同年份和不同月份,如下所示

我试过select distinct year(sc_ts) as years from posts where user_id = 1 order by years asc我在某种程度上无法适应那里的月份。或者这需要两个不同的语句和PHP处理。

我打算将其输出为

2009 - Mar, Apr, May
2010 - Apr, Jun, Jul

"2009-03-22 16:07:48"
"2009-04-22 16:07:48"
"2009-05-22 16:07:48"
"2010-04-22 16:07:48"
"2010-06-22 16:07:48"
"2010-07-22 16:07:48"
"2011-01-22 16:07:48"
"2011-02-22 16:07:48"
"2011-05-22 16:07:48"
"2011-06-22 16:07:48"
"2011-08-22 16:07:48"
"2012-01-22 16:07:48"
"2012-02-22 16:07:48"
"2012-03-22 16:07:48"
"2012-04-22 16:07:48"
"2012-08-22 16:07:48"

3 个答案:

答案 0 :(得分:4)

select distinct year(sc_ts) as years, group_concat(monthname(sc_ts)) as months from posts where user_id = 1 order by years asc

编辑:我最初使用了month(),它使用了monthname()来提供月份编号,而是返回月份的名称。

答案 1 :(得分:2)

SELECT x.`Year`, GROUP_CONCAT(x.`Month`) AS Months
FROM
    (
        SELECT DISTINCT YEAR(sc_ts) AS `Year`, MONTHNAME(sc_ts) AS `Month`
        FROM
            `posts`
        WHERE
            user_id = 1
        ORDER BY
            MONTH(sc_ts)
    ) x
GROUP BY
    x.`Year`
ORDER BY
    x.`Year`

答案 2 :(得分:0)

尝试SELECT distinct SUBSTRING(year(sc_ts), 6)