Question

I was wondering if the following is possible to achieve using a single select-join query.

Suppose we have two tables (rows of both refer to some events that happen in time). The first one, TableA has following columns:

ID,TimeOfOccurrence,SomeData1

the second one, TableB, looks similar:

ID,TimeOfOccurrence,SomeData2

The times of occurrences of events in TableA and TableB are always different, because they happen independently.

I select events from TableA, for example using the following query:

SELECT * FROM TableA WHERE SomeData1 LIKE 'something'

Now I want to make a join with TableB in the following manner: For every event in this result set I want to add ID and SomeData2 of an event from TableB which happened closest,let's say within 10 minutes interval, relatively to the particular row in the result set. In other words, I make a join based on the temporal adjacency of events in TableA and TableB.

Is there any way of doing this?

Was it helpful?

Solution

Try this approach:

select *
from A
join B
on  A.somedata1 
    between
       B.somedata2 - interval 10 minute
       and
       B.somedata2 + interval 10 minute

Demo --> http://www.sqlfiddle.com/#!2/d7ed9/1



----------- EDIT ---------------

Here is a demo with an example how to select the closest match
---> http://www.sqlfiddle.com/#!2/4b86b/12

SELECT id1, somedata1, id2, somedata2
FROM (
select id1, somedata1,
       min( abs( time_to_sec( somedata1 ) - 
            - time_to_sec( somedata2 ))) d_min
from A
join B
on  A.somedata1 
    between
       B.somedata2 - interval 10 minute
       and
       B.somedata2 + interval 10 minute
GROUP BY id1
) xx
JOIN B
ON xx.somedata1 
    between
       B.somedata2 - interval 10 minute
       and
       B.somedata2 + interval 10 minute
   AND abs( time_to_sec( somedata1 ) - 
            - time_to_sec( somedata2 ))
       <= d_min
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top