[英]MySQL: Find successive rows, where timestamp difference is less than x
我的表如下:
Field Type
id int(11)
user varchar(64)
date int(11)
key int(11)
日期采用時間戳格式。 我正在尋找一種方法來查找所有行,其中連續行之間的時間戳差異小於x。 可能嗎?
假設時間戳表示date
,這是可能的。 這是一個使用相關子查詢來獲取下一個date
值的版本:
select t.*
from (select t.*,
(select date
from yourtable t2
where t2.date > t.date
order by t2.date
limit 1
) as NextDate
from yourtable t
) t
where <difference calculation goes here>;
編輯:
以上是標准SQL。 在MySQL中,您也可以使用變量來執行此操作。
select t.*
from (select t.*, @nextdate as nextdate, @nextdate := date
from yourtable t
order by date desc
) t
where <difference calculation goes here>;
這種方法有兩個問題。 首先,變量的使用要求對結果集進行順序處理(在MySQL中並不重要,因為我認為這還是會發生)。 更重要的是,不能保證select
內容的評估順序。 換句話說,這可能有效,但不能保證有效。
順便說一下,許多其他數據庫都支持lead()
函數,這將是執行此操作的“正確”方法。 不幸的是,MySQL不支持窗口功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.