简体   繁体   中英

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!

try like below

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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