MySQL查询中的自动日期更改

时间:2014-01-17 12:15:35

标签: mysql sql date

我最近修改了一个每周运行的查询:

新查询

SELECT COUNT(*) as `count`, 
       `lang`, DATE(NOW()) as `week_ending` 
  FROM mytable.data 
 WHERE `date` > "2014-01-13" 
   AND `date` < "2014-01-20" 
 GROUP BY `lang`;

以旧日期为例的旧查询

 SELECT COUNT(*) as `count`, 
       `region`, DATE(NOW()) as `week_ending` 
   FROM mytable.data 
  WHERE `date` > DATE_ADD(DATE(NOW()), INTERVAL -1 WEEK) 
    AND `date` < DATE(NOW()) 
  GROUP BY `region`, DATE(NOW());

正如您所看到的,我已经自动将查询日期设置为每周更改一次,但是对于新查询,它没有像以前那样给我正确的结果?有没有其他方法我可以让每周更改日期,以便我可以尝试这种方法?

1 个答案:

答案 0 :(得分:2)

旧旧区别是旧查询使用当前日期 - 7天表示2014-01-10和2014-01-17 ...

因为我看到你正在使用不同的group by子句

SELECT COUNT(*) as `count`, `lang`, DATE(NOW()) as `week_ending` 
FROM mytable.data 
WHERE `date` > "2014-01-10" 
AND `date` < "2014-01-17" GROUP BY `lang`;