Amit Vais
Amit Vais

Reputation: 41

how to join tables not according to equality between two fields

I have a problem with a query in SQL oracle and I will be glad to hear if someone here can help me. so, I have two tables. One contains start time and end time of something (mostly long times) , and the second contains also start time and end time of something else (mostly short times). I want to join the second table to the first in a way that rows from the second table will be joined to the first when the time in the second are contained in the first. i will give an example:

first table:

name start end
---- ----- -----
a    10:00 12:00
b    16:00 18:00

second table:

name start end
---- ----- -----
c    11:30 11:45
d    16:15 17:45

so, the required table will join the second row in the second table to the second in the first, and similarly the first rows in the tables.

thanks!

Upvotes: 1

Views: 54

Answers (4)

Esteban P.
Esteban P.

Reputation: 2809

If i got you right, the range of the rows in the second table, have to be entirely included:

      SELECT *
        FROM Table_A A
  INNER JOIN Table_B B
          ON B.start BETWEEN A.start AND a.end
         AND B.end   BETWEEN A.start AND a.end

Upvotes: 0

Ajan Balakumaran
Ajan Balakumaran

Reputation: 1649

Assuming your time intervals in table1 don't overlap this would do,

Select *
From Table1 a
INNER JOIN Table2 b 
on b.start between a.start and a.end

Upvotes: 1

Gag Baghdasaryan
Gag Baghdasaryan

Reputation: 887

You can use the following expression in 'ON' clause in your join.

... ON (table1.start <= table2.start AND table1.end >= table2.end) .

Upvotes: 1

Zaynul Abadin Tuhin
Zaynul Abadin Tuhin

Reputation: 31991

try like below

select t1.*,t2.* from table1 t1 join table2 t2
on t1.start<=t2.start and t1.end>=t2.end

Upvotes: 1

Related Questions