说我有以下表格:
for_key1 (key)
val1,
start time 1 (key),
end time 1 (key)
for_key2 (key)
val2
start time 1 (key)
end time 2 (key)
注意:
我想生成一个查询,它返回tab1中的所有记录,这些记录与tab2中的任何记录都不相交(在时间透视图中)。
例如:
tab1
----
key, val1, start time = 1, end time = 4
key, val2, start time = 6, end time = 10
key, val3, start time = 13, end time = 17
tab2
----
key, val, start time = 5, end time = 8
查询将返回:
key, val1, start time = 1, end time = 4
key, val3, start time = 13, end time = 17
你知道我该怎么办?
答案 0 :(得分:0)
请参阅此答案Determine Whether Two Date Ranges Overlap,了解如何确定两个范围是否重叠。
根据以上答案,以下查询将给出重叠范围:
SELECT a.*
FROM tab1 a
JOIN tab2 b
ON a.start_time <= b.end_time
AND
a.end_time >= b.start_time
;
由于不需要重叠范围,只需在上述查询中否定连接条件:
SELECT a.*
FROM tab1 a
JOIN tab2 b
ON not ( a.start_time <= b.end_time
AND
a.end_time >= b.start_time
)
;
根据deMorgan的法律,这可以进一步简化为:
SELECT a.*
FROM tab1 a
JOIN tab2 b
ON a.start_time > b.end_time
OR
a.end_time < b.start_time
;