MYSQL无序返回日期

时间:2013-01-25 19:12:02

标签: php mysql sorting

我按月和年份列出所有新闻文章,以及当月发生的文章数量......

但是我注意到在新的一年里它只是按月分类而不是

这是我的SQL

$archive1_sql = "SELECT YEAR(`ndate`) AS 'year', MONTH(`ndate`) AS 'month', COUNT(`nid`) AS 'count'  FROM `weaponsnews` GROUP BY YEAR(`ndate`), MONTH(`ndate`) DESC";

它返回

December 2012 (1)
November 2012 (11)
October 2012 (6)
September 2012 (8)
August 2012 (16)
July 2012 (8)
June 2012 (6)
May 2012 (12)
April 2012 (4)
March 2012 (2)
February 2012 (4)
January 2013 (1)

我想要它做的就像这样

January 2013 (1)
December 2012 (1)
November 2012 (11)
October 2012 (6)
September 2012 (8)
August 2012 (16)
July 2012 (8)
June 2012 (6)
May 2012 (12)
April 2012 (4)
March 2012 (2)
February 2012 (4)

我该怎么做?

3 个答案:

答案 0 :(得分:2)

GROUP BY更改为:

GROUP BY YEAR(`ndate`) DESC, 
         MONTH(`ndate`) DESC

如果没有ORDER BY,MySQL具有(非标准SQL)功能,它根据GROUP BY顺序对结果进行排序。它还允许ASCDESC个关键字。

来自MySQL文档 SELECT syntax

  
      
  • 如果您使用GROUP BY,则会根据GROUP BY对输出行进行排序,就好像您有相同列的ORDER BY 一样。为避免GROUP BY生成的排序开销,请添加ORDER BY NULL

    SELECT a, COUNT(b) FROM test_table GROUP BY a ORDER BY NULL;
    
  •   
  • MySQL扩展了GROUP BY子句,以便您还可以在子句中指定的列之后指定ASCDESC

    SELECT a, COUNT(b) FROM test_table GROUP BY a DESC;
    
  •   

答案 1 :(得分:2)

使用YEAR添加DESC

SELECT
  YEAR(`ndate`) AS 'year',
  MONTH(`ndate`) AS 'month',
  COUNT(`nid`) AS 'count'
FROM `weaponsnews`
GROUP BY YEAR(`ndate`) , MONTH(`ndate`)
ORDER BY YEAR(`ndate`) DESC , MONTH(`ndate`) DESC

答案 2 :(得分:2)

要按(按时间顺序)顺序获取记录,请使用“按命令排序DESC”:

SELECT
  YEAR(`ndate`) AS 'year',
  MONTH(`ndate`) AS 'month',
  COUNT(`nid`) AS 'count'
FROM `weaponsnews`
GROUP BY YEAR(`ndate`) , MONTH(`ndate`)
ORDER BY ndate DESC

然后你可以按照你想要的任何方式分组(几天,几周......),你不需要改变你的'order by'陈述。