I would like to know how to run a SQL query that returns events that have a time that is in a valid segment.
For example, I have the two tables,
Event
event_id event_time
0 134
1 434
2 4300
Segment
segment_type segment_start_time segment_end_time
data1 100 130
data1 200 500
data1 700 8000
veto1 400 440
data2 150 450
data2 4000 5000
veto2 175 200
I want a query that would return
event_id event_time
1 434
2 4300
I was thinking something like
SELECT *
FROM event
WHERE
event.event_time > (SELECT segment.segment_start_time FROM segment)
AND
event.event_time < (SELECT segment.segment_end_time FROM segment)
But this just returns nothing. What am I doing wrong?
The next step I want to do is to find events times that are;
between a ‘data’ segment start time and end time AND
NOT between a ‘veto’ segment start time and end time
And finally, I actually have two type of data segments and veto segments. I want to return events that have times;
between a ‘data1’ segment start time and end time AND
between a ‘data2’ segment start time and end time AND
NOT between a ‘veto1’ segment start time and end time AND
NOT between a ‘veto2’ segment start time and end time
So from my example table above, the output I want would be
event_id event_time
2 4300
I’m going to assume that you will normally have more entries in the event table than in the segment table.
This allow the pseduo-code to be “for every segment, check which events are valid”. This allows range-seeks on the event table.
The
GROUP BYis only needed if different entries insegmentcan overlap.The alternative approach is with the pseudo-code “for each event, check if any segments overlap it”.
Doing so, however, will not allow a range seek (see my comment on @MarkByers answer).
EDIT Following edit to question…
As far as I understand the changes, an event should only be returned if…