Search code examples
sqlsearchcomparison-operators

Using greater-than or equal/less-than or equal twice in one SQL query


I'm trying to create what is basically a timestamp search query. The user puts in a beginning time and end time for a desired reservation and the search finds any current reservations for that room during that time period. If a match is found, the user is told that the room is already reserved.

The problem I'm running into is that when I send this query:

SELECT * FROM event WHERE begintime <= '$start' AND endtime >= '$end' AND room = '$room';

I get no records. The variables are holding the right information, so I suspect that the way I'm using the arithmetic operators is wrong. I've looked around plenty and found many examples of both types of comparisons being used in one query, but only for one column. I haven't found any examples of someone comparing a value against one column and a value against another column like this all in one query.

Anyone have any idea what I'm doing wrong? Any help is much appreciated. Thanks!

EDIT: I have the timestamp set in Epoch time, so the start time put into the search will either be greater than or equal to what is already in the database to fall between the start and end time. Inverse goes for the end time, as the time put into the search will either be less than or equal to the end time in the database to fall between the start and end time. Flipping the signs would find times outside the reservation in the database. Inputs are validated.


Solution

  • To find that you have different scenarios:

    • A reservation starts in your search-period
    • A reservation ends in you search-period
    • A reservation starts before you search-period and ends after it.

    You have to search all three

    SELECT * FROM event WHERE ((begintime <= '$start' AND endtime >= '$end') OR (begintime >= '$start' AND endtime <= '$start')  OR (begintime >= '$end' AND endtime <= '$end')) AND room = '$room';