如何将数据限制为仅最后5个结果

时间:2013-07-16 13:12:02

标签: mysql

我有下面的查询来获取行数并按周分组。它很棒。

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

如何修改此项,以便在不使用ORDER BY weekno DESC LIMIT 5的情况下仅选择最后5个结果,以免改变数据的排列方式。感谢

2 个答案:

答案 0 :(得分:6)

您可以添加ORDER BY weekno DESC LIMIT 5并将查询推送到子查询中,然后让外部查询重新排序:

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

答案 1 :(得分:3)

只需使用mysql中使用的limit

在代码limit 5之后添加ORDER BY weekno ASC。意味着在查询结束时添加它。

这是the tutorial

实施例

使用以下查询:

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