简体   繁体   English

Mysql选择差异为10分钟的所有行

[英]Mysql Select all rows with 10 minute difference

I have a table with timestamp and I want to retrieve all the records with 10 minutes difference between each other. 我有一个带时间戳的表,我想要检索彼此之间有10分钟差异的所有记录。 I give you an example: I have in my database 4 dates: 我举个例子:我在我的数据库中有4个日期:

01-12-2015 15:45:10
01-12-2015 15:55:10
01-12-2015 15:25:10
01-12-2015 15:15:10

I want to retrieve only the 2 dates that have 10 minutes difference between each other. 我想只检索彼此之间有10分钟差异的2个日期。

I don't want to get all records where the timestamp is within 10 minutes of the current timestamp. 我不希望得到时间戳在当前时间戳的10分钟内的所有记录。 I want to select all the records having a difference of 10 minutes between them. 我想选择它们之间相差10分钟的所有记录。 So in my example I want to select on the dates: 所以在我的例子中我想选择日期:

01-12-2015 15:45:10
01-12-2015 15:55:10

These 2 dates should have a difference of 10 minutes between them. 这两个日期之间应该相差10分钟。 How I can do that? 我怎么能这样做?

You can use now() to get the current time. 您可以使用now()来获取当前时间。 So: 所以:

select t.*
from t
where t >= date_sub(now(), interval 10 minute);

Here's the example how you compute if the two dates has 10 minutes difference in the current time 1st param let say the current time. 下面是如何计算两个日期在当前时间内有10分钟差异的示例。第一个参数说明当前时间。 SELECT TIMEDIFF('2015-12-11 08:20:00','2015-12-11 08:10:00')

I hope you have an index. 我希望你有一个索引。 Make an JOIN on index = index+1 -> Every row is connected with the previous one. 在index = index + 1上创建一个JOIN - >每一行都与前一行连接。 Then calculate the time diff and pick only those rows with diff more then 10 minutes. 然后计算时间差异并仅选择那些差异大于10分钟的行。

SELECT *
FROM dates AS a LEFT OUTER JOIN dates AS b 
ON a.id = b.id+1
WHERE a.timestamps-b.timestamps >= 600

Have a look at this fiddle: http://sqlfiddle.com/#!9/31b0eb/3 看看这个小提琴: http ://sqlfiddle.com/#!9/ 31b0eb/3

Try: 尝试:

Select * from a where a.id not in
 (select b.id from a b where TIMEstampDIFF(SECOND,a.mydate,b.mydate)<=600)
and a.id not in
 (select c.id from a c where TIMEstampDIFF(SECOND,a.mydate,c.mydate)>600)

You can fetch data from sql query and write the logic in your php file as follows: 您可以从sql查询中获取数据并在php文件中编写逻辑,如下所示:

$select =   mysql_query("SELECT your_datetime_column_name as time,UNIX_TIMESTAMP(your_datetime_column_name) as time_string FROM your_table_name");
 $result = mysql_fetch_array($select);
    $final_result= NULL;
    $j=0;
    foreach($result as $ff)
    {
       foreach($result as $ff11)
    {
       if(abs($ff11['time_string'] - $ff['time_string']) ==600 ){ 
       $final_result[$j]['time1']=$ff['time'];
           $final_result[$j]['time2']=$ff11['time'];
       $j++;
        }
    }
    }

and in array $final_result you will get all the dates pair with 10 min difference. 并且在数组$ final_result中,您将获得所有日期配对,差异为10分钟。 hope it will help you. 希望它会对你有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM