I'm trying to select all rows from a table that are included into a given time range,
Suppose I have the following table:
`range` ( `id`, `from`, `to` )
Where from
and to
have the type: VARCHAR( 19 )
(for YYYY-MM-DD HH:II:SS).
As these attributes are VARCHAR typed, I'm comparing dates with str_to_date
, such as this explainations example: varchar date time comparison issue
So I first define my time range (with PHP):
$rangeNow = Date( 'Y-m-d H:i:s' );
$rangeTo = Date( 'Y-m-d H:i:s', strtotime( '+10 minutes', strtotime( $rangeNow) ) );
$rangeFrom = Date( 'Y-m-d H:i:s', strtotime( '-10 minutes', strtotime( $rangeTo ) ) );
Here as you can see, it's a range of 20 min:
echo $rangeFrom.' => '.$rangeTo;
>> 2022-04-18 17:02:29 => 2022-04-18 17:22:29
But when I add this condition to my MySQL query (to have all rows starting or ending in this range), I don't get any rows:
WHERE (
(
str_to_date( `range`.`from`, "%Y-%m-%d %h-%i-%s" )
BETWEEN str_to_date( "'.$rangeFrom.'", "%Y-%m-%d %h-%i-%s" )
AND str_to_date( "'.$rangeTo.'", "%Y-%m-%d %h-%i-%s" )
)
OR
(
str_to_date( `range`.`to`, "%Y-%m-%d %h-%i-%s" )
BETWEEN str_to_date( "'.$rangeFrom.'", "%Y-%m-%d %h-%i-%s" )
AND str_to_date( "'.$rangeTo.'", "%Y-%m-%d %h-%i-%s" )
)
)
But in my range table, I have the following rows:
(
[0] => Array
(
[from] => 2022-04-18 16:38:41
[to] => 2022-04-18 17:12:16
)
[1] => Array
(
[from] => 2022-04-18 16:36:38
[to] => 2022-04-18 16:38:28
)
[2] => Array
(
[from] => 2022-04-18 16:33:06
[to] => 2022-04-18 16:33:06
)
)
It should return the first-one (that is in this range) and no others, do you have any idea about why no rows are selected?
(without the above WHERE conditions, it select all rows)