简体   繁体   English

如何根据两个字段之间的相等性来连接表

[英]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. 我在SQL oracle中遇到查询问题,我很高兴听到有人在这里可以帮助我。 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”子句中使用以下表达式。

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

Assuming your time intervals in table1 don't overlap this would do, 假设你在table1中的时间间隔不重叠,这样做,

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

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

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