提问者:小点点

MySQL-从表B搜索位于表A的多个时间范围内的记录


MySQL版本=5.7.29这是我的表A:

╔════════════════════╦════════════════════╦═════════════╗
║StartDateEndDateVar          ║  
╠════════════════════╬════════════════════╬═════════════╣             
║2020-06-19 00:00:00 ║2020-06-19 00:20:00b            ║
║2020-06-19 00:20:01 ║2020-06-19 00:40:00a            ║
║2020-06-19 00:40:01 ║2020-06-19 01:00:00a            ║
║2020-06-19 01:00:01 ║2020-06-19 01:20:00b            ║  
║2020-06-19 01:20:01 ║2020-06-19 01:40:00a            ║
║2020-06-19 01:40:01 ║2020-06-19 02:00:00b            ║
║2020-06-19 02:00:01 ║2020-06-19 02:20:00a            ║
║2020-06-19 02:20:01 ║2020-06-19 02:40:00b            ║
╚════════════════════╩════════════════════╩═════════════╝

这是我的B桌:

╔════════════════════╦════════════════════╦═════════════╗
║cDateVal1Val2         ║  
╠════════════════════╬════════════════════╬═════════════╣             
║2020-06-19 00:01:00 ║102                 ║a1           ║
║2020-06-19 00:25:21 ║05                  ║a2           ║
║2020-06-19 00:49:01 ║94                  ║b3           ║
║2020-06-19 01:10:01 ║04                  ║b23          ║  
║2020-06-19 01:15:04 ║10                  ║1            ║
║2020-06-19 01:28:01 ║56                  ║2            ║
║2020-06-19 02:00:09 ║29                  ║3            ║
║2020-06-19 02:38:01 ║24                  ║4            ║
╚════════════════════╩════════════════════╩═════════════╝

我想要表B中的所有行,其中cDate位于表A中的StartDate和EndDate之间,其中var='A'

假设表A中每个Var只有1个时间戳:

╔════════════════════╦════════════════════╦═════════════╗
║StartDateEndDateVar          ║  
╠════════════════════╬════════════════════╬═════════════╣             
║2020-06-19 00:00:00 ║2020-06-19 00:20:00b            ║
║2020-06-19 00:20:01 ║2020-06-19 00:40:00a            ║
╚════════════════════╩════════════════════╩═════════════╝

下面的查询会起作用

select * from tableB where Cdate >= (select startDate from tableA where var = 'a') and cDate <= (select EndDate from tableA where var = 'b')

但是在当前每个Var有多个时间戳的情况下,我该如何做到这一点呢?


共2个答案

匿名用户

在您的条件中加入两个表:

select distinct b.cDate, b.Val1, b.Val2
from b inner join a
on b.cDate between a.StartDate and a.EndDate and a.Var = 'a'

或带有exists:

select b.* from b
where exists (
  select 1 from a 
  where b.cDate between a.StartDate and a.EndDate and a.Var = 'a'
)

匿名用户

使用exists:

select b.*
from tableb b
where exists (
    select 1 from tablea 
    where b.cDate >= a.startDate and b.cDate < a.endDate
)

您可能需要根据您的确切需求调整不等式-我使用了半开间隔(低值为>=,高值为<)。

相关问题