MySQL版本=5.7.29这是我的表A:
╔════════════════════╦════════════════════╦═════════════╗
║StartDate ║EndDate ║Var ║
╠════════════════════╬════════════════════╬═════════════╣
║2020-06-19 00:00:00 ║2020-06-19 00:20:00 ║b ║
║2020-06-19 00:20:01 ║2020-06-19 00:40:00 ║a ║
║2020-06-19 00:40:01 ║2020-06-19 01:00:00 ║a ║
║2020-06-19 01:00:01 ║2020-06-19 01:20:00 ║b ║
║2020-06-19 01:20:01 ║2020-06-19 01:40:00 ║a ║
║2020-06-19 01:40:01 ║2020-06-19 02:00:00 ║b ║
║2020-06-19 02:00:01 ║2020-06-19 02:20:00 ║a ║
║2020-06-19 02:20:01 ║2020-06-19 02:40:00 ║b ║
╚════════════════════╩════════════════════╩═════════════╝
这是我的B桌:
╔════════════════════╦════════════════════╦═════════════╗
║cDate ║Val1 ║Val2 ║
╠════════════════════╬════════════════════╬═════════════╣
║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个时间戳:
╔════════════════════╦════════════════════╦═════════════╗
║StartDate ║EndDate ║Var ║
╠════════════════════╬════════════════════╬═════════════╣
║2020-06-19 00:00:00 ║2020-06-19 00:20:00 ║b ║
║2020-06-19 00:20:01 ║2020-06-19 00:40:00 ║a ║
╚════════════════════╩════════════════════╩═════════════╝
下面的查询会起作用
select * from tableB where Cdate >= (select startDate from tableA where var = 'a') and cDate <= (select EndDate from tableA where var = 'b')
但是在当前每个Var有多个时间戳的情况下,我该如何做到这一点呢?
在您的条件中加入两个表:
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
)
您可能需要根据您的确切需求调整不等式-我使用了半开间隔(低值为>=
,高值为<
)。