Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql date select rows within X seconds range of each other

My sql table is something like (message,created)

I want to select those rows which are within X seconds from each other. Say the last message is within X seconds from NOW(), then it should select it. If the second last message is within X seconds from the last message then it should select it too. In other words each row should be compared with the next row and checked. For the last row it should be check with say NOW(). Basically I want the last session of messages (i.e. last set of messages that we linked to each other, assuming that consequtive messages within X seconds are linked to each other)

I have no idea how to go about writing an SQL query for this. Is it even possible?

Thank you very much for your time.

like image 578
Alec Smart Avatar asked May 08 '09 09:05

Alec Smart


People also ask

How can I get data between two timestamps in SQL?

As stated above, the format of date and time in our table shall be yyyy:mm: dd hh:mm: ss which is implied by DATETIME2. The time is in a 24-hour format. Syntax: SELECT * FROM TABLE_NAME WHERE DATE_TIME_COLUMN BETWEEN 'STARTING_DATE_TIME' AND 'ENDING_DATE_TIME';

How can I get data between two dates in SQL?

To find the difference between dates, use the DATEDIFF(datepart, startdate, enddate) function. The datepart argument defines the part of the date/datetime in which you'd like to express the difference.


1 Answers

This script works in SQLServer. You should be able to take out the select statement and run it in MySQL.

DECLARE @Messages TABLE (Message VARCHAR(10), Created DATETIME)
DECLARE @Interval FLOAT

-- Interval is 1 day.
SET @Interval = 1

-- These should be in result
INSERT INTO @Messages VALUES ('Message1', GetDate())    
INSERT INTO @Messages VALUES ('Message2', GetDate()-1)
-- These should not be in result
INSERT INTO @Messages VALUES ('Message3', GetDate()-3)
INSERT INTO @Messages VALUES ('Message4', GetDate()-5)

SELECT m1.Message, m1.Created
FROM @Messages m1
     INNER JOIN @Messages m2 ON m2.Created <= m1.Created + @Interval                                
                                AND m2.Created >= m1.Created
                                AND m2.Message <> m1.Message
UNION ALL SELECT m2.Message, m2.Created
FROM @Messages m1
     INNER JOIN @Messages m2 ON m2.Created <= m1.Created + @Interval                                
                                AND m2.Created >= m1.Created
                                AND m2.Message <> m1.Message
ORDER BY Created
like image 168
Lieven Keersmaekers Avatar answered Nov 14 '22 21:11

Lieven Keersmaekers