我有一张每小时记录如下的桌子:
如你所见,每条记录都有1小时的时差,但突出显示的记录有超过1小时的时差。我需要一个查询,当间隔超过1小时时,该查询应同时返回上限值(id 11379728
)和下限值(id 11378448
)。
任何帮助都将不胜感激。
注意:-请忽略last datetime列,因为它有不同的用途。
最佳答案
我有一个有效的解决方案(对我来说很完美):
SET @lastDate := (SELECT dateColumn FROM table ORDER BY dateColumn ASC LIMIT 1);
SELECT @lastDate as lastDate, HOUR(TIMEDIFF(dateColumn, @lastDate)) as diff, @lastDate := dateColumn, dateColumn
FROM table
group by dateColumn
having diff > 1
order by dateColumn ASC;
在某些情况下,mysql 5.5和5.6会对
HAVING
子句给出不同的结果。上面的查询在mysql 5.5上运行良好。我已经创建了另一个版本以在两个版本上运行,类似如下:SET @lastDate := (SELECT dateColumn FROM table ORDER BY dateColumn ASC LIMIT 1);
SELECT * FROM (SELECT @lastDate as lastDate, HOUR(TIMEDIFF(dateColumn, @lastDate)) AS diff, @lastDate := dateColumn, dateColumn FROM table GROUP BY dateColumn ORDER BY dateColumn ASC) AS tbl WHERE tbl.diff > 1;