2

我有下面的查询来获取行数并按周对它们进行分组。它工作得很好。

SELECT  
    WEEKOFYEAR(searched_on) AS weekno,
    COUNT(*) AS num_search, 
    SUBDATE(searched_on, INTERVAL WEEKDAY(searched_on) DAY), INTERVAL + 0 DAY AS date_of_week,              
    FROM table 
    GROUP BY WEEK(DATE_SUB(searched_on, INTERVAL 1 DAY)) ORDER BY weekno ASC

我如何修改它以便只选择最后 5 个结果而不使用ORDER BY weekno DESC LIMIT 5,以免改变数据的排列方式。谢谢

4

2 回答 2

6

You could add the ORDER BY weekno DESC LIMIT 5 and push the query into a subquery, then have the outer query reorder ascending:

SELECT * FROM (
  SELECT  
    WEEKOFYEAR(searched_on) AS weekno,
    COUNT(*) AS num_search, 
    SUBDATE(searched_on, INTERVAL WEEKDAY(searched_on) DAY), INTERVAL + 0 DAY AS date_of_week,              
    FROM table 
    GROUP BY WEEK(DATE_SUB(searched_on, INTERVAL 1 DAY))
    ORDER BY weekno DESC LIMIT 5
) inner
ORDER BY weekno
于 2013-07-16T13:15:53.947 回答
3

只需使用limitmysql中使用的。

limit 5在代码之后添加ORDER BY weekno ASC。表示在查询末尾添加它。

这是教程

例子

使用以下查询:

SELECT  
    WEEKOFYEAR(searched_on) AS weekno,
    COUNT(*) AS num_search, 
    SUBDATE(searched_on, INTERVAL WEEKDAY(searched_on) DAY), INTERVAL + 0 DAY AS date_of_week,              
    FROM table 
    GROUP BY WEEK(DATE_SUB(searched_on, INTERVAL 1 DAY)) ORDER BY weekno ASC 
    LIMIT 5 OFFSET (num_search-5) //add this line 
于 2013-07-16T13:15:38.923 回答