Checking for date range conflicts in MySQL

前端 未结 4 1545
不思量自难忘°
不思量自难忘° 2021-02-02 03:25

I am writing a hotel booking system. after lots of studying (including stack overflow) i wrote this sql to find out free rooms:

SELECT
*
FROM room
WHERE
    room         


        
4条回答
  •  自闭症患者
    2021-02-02 03:41

    The problem you're having is that your query is not sufficiently robust. When you break down the problem, what you have is this:

    If the range defined by $check_in and $check_out overlaps the range defined by checkin and checkout in any way, then the room is booked. Otherwise, it is free.

    This means that:

    • If $check_in >= checkin and $check_in <= checkout, the room is BOOKED
    • OR If $check_out >= checkin and $check_out <= checkout, the room is BOOKED
    • OR If $check_in <= checkin and $check_out >= checkout, the room is BOOKED

    So, you need to represent both of these scenarios in your subquery in order to get the information you're looking for.

    Also, you will hopefully be using datetime for your comparisons and not just time, otherwise you will have side effects.

    EDIT: SQL Query

    (Keep in mind that there is more than one way to skin a cat, so to speak. I'm just providing an example that keeps with what you already have as much as possible. Once again, I'm also assuming that checkin, checkout, $check_in, and $check_out will all resolve to datetime types)

    SELECT *
    FROM room
    WHERE room_id NOT IN
    (SELECT room_id 
     FROM bookings
     WHERE
       (checkin <= '$check_in' AND checkout >= '$check_in') OR
       (checkin <= '$check_out' AND checkout >= '$check_out') OR
       (checkin >= '$check_in' AND checkout <= '$check_out'))
    

提交回复
热议问题