在DATE_FORMAT之后按日期排序MySql

时间:2012-10-15 22:53:06

标签: mysql date sql-order-by union

我有两个表,fbpost和fbalbum,每个表都有一个名为DATETIME的{​​{1}}列。我找到了每月的专辑数量,以及每月的帖子数量,并将它们加在一起。

这是我的查询(按照描述的方式工作):

createdTime

这给出了结果:

SELECT  createdTime, itemCount FROM 
        (SELECT DATE_FORMAT(createdTime, '%m-%Y') AS createdTime, COUNT(*) AS itemCount FROM fbpost WHERE page_id =2 
        GROUP BY YEAR(createdTime), MONTH(createdTime)
        UNION ALL
        SELECT DATE_FORMAT(createdTime, '%m-%Y') AS createdTime, COUNT(*) AS itemCount FROM fbalbum WHERE page_id=2
        GROUP BY YEAR(createdTime), MONTH(createdTime)) AS foo
GROUP BY createdTime

但我希望结果如下:

01-2009 | 173
01-2010 | 21
01-2011 | 521
01-2012 | 776
02-2009 | 117
02-2010 | 158
02-2011 | 678
...

我怎样才能做到这一点?

注意: 01-2009 | 173 02-2009 | 56 03-2009 | 543 04-2009 | 211 05-2009 | 723 06-2009 | 55 07-2009 | 521 ... 会提供一个字符串,而不是DATE_FORMAT(),因此您无法按日期排序。但是,如果我在两个嵌套的select语句中取出DATETIME,我会在大多数月份获得2行,因为那样会离开这一天。虽然每个嵌套选择每月只有一行,但它们通常会有所不同,因为一个月中的最后一项可能在任何一天。

1 个答案:

答案 0 :(得分:1)

在您的外部查询之前不要使用DATE_FORMAT

SELECT DATE_FORMAT(a.createdTime, '%m-%Y') AS createdTime, SUM(a.itemCount) AS itemCount
FROM
    (SELECT DATE(createdTime) AS createdTime, COUNT(*) AS itemCount 
    FROM fbpost WHERE page_id = 2
    GROUP BY DATE(createdTime)
    UNION ALL
    SELECT DATE(createdTime) AS createdTime, COUNT(*) AS itemCount
    FROM fbalbum WHERE page_id = 2
    GROUP BY DATE(createdTime)) a
GROUP BY YEAR(a.createdTime), MONTH(a.createdTime)

See it in action *

* 演示没有page_id