Question

I want to select rows which are between 2 time-fields. This is working fine

$hour = date('H:i');
$time = " AND ( ( time1 IS NULL AND time2 IS NULL ) OR ( '$hour'  BETWEEN  time1 AND time2 ) ) ";

But my problem is, that the call must work on queries where time1 can be larger than time2 too.

like time1=18:00:00 and time2=02:00:00

In this case, the query must match eg. 01:00:00 too?

Is there a way to do this in sql directly ( instead of PHP )?

Was it helpful?

Solution

First, I don't think it is a good idea to get the time in the application code and then compare to values in the database. MySQL offers many functions to manipulate datetimes.

I think the logic that you want is:

AND ((time1 < time2 and '$hour' BETWEEN time1 AND time2) or
     (time1 > time2 and '$hour' NOT BETWEEN time1 and time2)
    )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top