Note that 'x BETWEEN y AND z
' assumes y
is less than z
; it never returns anything otherwise. It is equivalent to 'x >= y AND x <= z
'.
Given that the off time is after midnight in this case, then you need to do a much more complex condition:
SELECT zdate
FROM zones
WHERE (time_on < time_off AND '18:21:00' BETWEEN time_on AND time_off)
OR (time_on > time_off AND ('18:21:00' > time_on OR '18:21:00' < time_off))
The first condition is the normal one for time on is on the same day as time off. The second alternative checks that the target time is after the time on (and implicitly before midnight) or that it is before the time off (and hence between midnight and the time off).
For greater symmetry:
SELECT zdate
FROM zones
WHERE (time_on < time_off AND ('18:21:00' > time_on AND '18:21:00' < time_off))
OR (time_on > time_off AND ('18:21:00' > time_on OR '18:21:00' < time_off))
Example output using IBM Informix Dynamic Server (IDS) 11.50.FC4W1 on MacOS X 10.6.2. IDS uses 'DATETIME HOUR TO SECOND' as the equivalent of the TIME type in standard SQL.
CREATE TEMP TABLE zones
(
time_on DATETIME HOUR TO SECOND NOT NULL,
time_off DATETIME HOUR TO SECOND NOT NULL
);
INSERT INTO zones VALUES ('09:00:00', '02:00:00');
INSERT INTO zones VALUES ('07:00:00', '19:00:00');
INSERT INTO zones VALUES ('20:00:00', '22:00:00');
INSERT INTO zones VALUES ('10:00:00', '15:15:00');
INSERT INTO zones VALUES ('21:00:00', '04:00:00');
CREATE TEMP TABLE times
(
zdate DATETIME HOUR TO SECOND NOT NULL
);
INSERT INTO times VALUES ('18:21:00');
INSERT INTO times VALUES ('08:30:00');
INSERT INTO times VALUES ('20:30:00');
INSERT INTO times VALUES ('12:30:00');
SELECT zdate, time_on, time_off
FROM zones CROSS JOIN times
WHERE (time_on < time_off AND (zdate > time_on AND zdate < time_off))
OR (time_on > time_off AND (zdate > time_on OR zdate < time_off))
ORDER BY zdate, time_on, time_off
Output data:
08:30:00 07:00:00 19:00:00
12:30:00 07:00:00 19:00:00
12:30:00 09:00:00 02:00:00
12:30:00 10:00:00 15:15:00
18:21:00 07:00:00 19:00:00
18:21:00 09:00:00 02:00:00
20:30:00 09:00:00 02:00:00
20:30:00 20:00:00 22:00:00
I think that looks correct.