获取最近8天数据的Mysql查询

时间:2014-03-05 08:39:40

标签: mysql

我正在尝试使用以下查询获取过去8天的数据。但是我今天得到了额外的记录。以下是查询:

SELECT
  DATE_FORMAT(date,'%d-%m-%Y'),
  IFNULL(DATE_FORMAT(ar_stime,'%d-%m-%Y %h:%i:%s'),' '),
  IFNULL(DATE_FORMAT(ar_etime,'%d-%m-%Y %h:%i:%s'),' '),
  IFNULL(ar_eltime,' '), 
  IF(ar_status='Aborted','Running',ar_status)
FROM etl.etl_status 
WHERE date =CURDATE()

UNION

SELECT
  DATE_FORMAT(date,'%d-%m-%Y'),
  IFNULL(DATE_FORMAT(ar_stime,'%d-%m-%Y %h:%i:%s'),' '),
  IFNULL(DATE_FORMAT(ar_etime,'%d-%m-%Y %h:%i:%s'),' '),
  IFNULL(ar_eltime,' '),
  ar_status
FROM etl.etl_status es 
WHERE date > DATE_SUB(DATE_SUB(CURDATE(),INTERVAL 1 day), INTERVAL 7 DAY)

知道我哪里错了吗?

2 个答案:

答案 0 :(得分:0)

用于8天前的日期:

select date_format(date,'%d-%m-%Y'),
ifnull(date_format(ar_stime,'%d-%m-%Y %h:%i:%s'),' '),
ifnull(date_format(ar_etime,'%d-%m-%Y %h:%i:%s'),' '),
ifnull(ar_eltime,' '), 
if(ar_status='Aborted','Running',ar_status)
from etl.etl_status 
where date =CURDATE()
union
select date_format(date,'%d-%m-%Y'),
ifnull(date_format(ar_stime,'%d-%m-%Y %h:%i:%s'),' '),
ifnull(date_format(ar_etime,'%d-%m-%Y %h:%i:%s'),' '),
ifnull(ar_eltime,' '),
ar_status
from etl.etl_status es 
WHERE t.date >= DATE_ADD(CURDATE(), INTERVAL -8 DAY);

查看DATE_ADD文档。

或者您可以使用:

select date_format(date,'%d-%m-%Y'),
ifnull(date_format(ar_stime,'%d-%m-%Y %h:%i:%s'),' '),
ifnull(date_format(ar_etime,'%d-%m-%Y %h:%i:%s'),' '),
ifnull(ar_eltime,' '), 
if(ar_status='Aborted','Running',ar_status)
from etl.etl_status 
where date =CURDATE()
union
select date_format(date,'%d-%m-%Y'),
ifnull(date_format(ar_stime,'%d-%m-%Y %h:%i:%s'),' '),
ifnull(date_format(ar_etime,'%d-%m-%Y %h:%i:%s'),' '),
ifnull(ar_eltime,' '),
ar_status
from etl.etl_status es 
where date > ( CURDATE() - INTERVAL 8 DAY )

答案 1 :(得分:0)

您是否尝试过简单:

SELECT *
FROM `etl_status `
WHERE `date` >= DATE_SUB(CURDATE(), INTERVAL 8 DAY)