Mysql,检索超过X天的记录

时间:2016-07-06 17:45:22

标签: mysql

这是一个存储日志/活动表:

log [id, date, time]

我想通过引用最早的(第一次插入的)

来检索超过X天的记录

这样的事情:

SELECT * FROM log
WHERE 
(date BETWEEN MIN(date) AND DATE_ADD(MIN(date), INTERVAL X DAY))
GROUP BY date
ORDER BY date, Time

更新: 虽然我提出了SELECT案例的问题,但事实是我需要删除记录(DELETE)。认为它是相同的(我错了),事实是它不能在同一个表上使用嵌套的SELECT进行DELETE。 (并且有道理)。

看到结尾很复杂,需要不止一个句子,最后我考虑将代码分成两个查询,第一个用于获取第一个插入元素的日期,第二个用于清除。

$sql1 = "SELECT MIN(date) as MinDate FROM `log`";

// Execute the query and gets the result row using whatever database driver[..]
$minDate = $rowQuery["MinDate"]

$sql2 = "DELETE FROM `log` WHERE Date > DATE_ADD('".$minDate."', INTERVAL ".$days." DAY)";

感谢。

1 个答案:

答案 0 :(得分:2)

如果你聚合函数,你应该使用having而不是where

SELECT * FROM log
where date in (select date from log 
         having date BETWEEN Min(date) AND DATE_ADD(date, INTERVAL X DAY))
GROUP BY date) 
ORDER BY date, time

但是对于选择这是更好的

SELECT * FROM `log`
where DateF  BETWEEN (select min(DateF) from `log`) 
            AND DATE_ADD((select min(DateF) from `log`), INTERVAL 2 DAY)
ORDER BY DateF, TimeF

http://sqlfiddle.com/#!9/85d9f0/4

通过subselect执行不可能删除的事实,您可以使用临时表     create table temp_log(dateF datetime(6));

insert in temp_log 
select DateF FROM `log`
             where DateF  BETWEEN (select min(DateF) from `log`) 
             AND DATE_ADD((select min(DateF) from `log`)

delete from  `log` as a
inner join temp_log  t on  t.DateF = a.DateF;


drop table temp_log ;