使用我的sql从表中获取下一个最后n个元素

时间:2014-08-04 15:15:42

标签: mysql group-by limits

我有一个这样的表来跟踪每小时访问我的网站:

id  | year | month | day | hour | date          | visit
 1    1391    12      1     10     2012-11-10       15
...    ...    ...    ...   ...         ...              ...

我使用此查询来获取最近7天的访问量。

SELECT Sum(visit), `day`, `month`, `year`, WEEKDAY(date) as wd 
FROM tablename GROUP BY date ORDER BY date DESC LIMIT 7;

现在我的问题是:我如何在这7天之前7天取货?

(年,日,月是我的本地日期格式,我想在注册时更改一次)

2 个答案:

答案 0 :(得分:2)

使用offset

SELECT Sum(visit), `day`, `month`, `year`, WEEKDAY(date) as wd 
FROM tablename
GROUP BY date
ORDER BY date DESC
LIMIT 7 OFFSET 7;

答案 1 :(得分:1)

我不喜欢在这里使用LIMIT获取过去7天的想法,我更喜欢WHERE子句。

我会将您的查询更改为:

  SELECT SUM(visit), `day`, `month`, `year`, WEEKDAY(date) as wd 
    FROM tablename
   WHERE date >= CURDATE() - INTERVAL 7 DAYS
GROUP BY date 
ORDER BY date DESC;

然后获得前7天:

  SELECT SUM(visit), `day`, `month`, `year`, WEEKDAY(date) as wd 
    FROM tablename
   WHERE date BETWEEN CURDATE() - INTERVAL 14 DAYS AND CURDATE() - INTERVAL 8 DAYS
GROUP BY date 
ORDER BY date DESC;

我也不喜欢在表格中存储本地日期格式的想法..你正在复制数据,在查询时应该很容易转换日期。