doutao1939 2014-05-21 15:33
浏览 34
已采纳

检查可用性并列出可用房间[关闭]

These days I am working hard for my degree project on Hotel Room Reservation System.
Now I strucked at the check availability stage.
Here is my table structure


Bookings

`ID` int(11) 
`roomID` int(11)
`startDate` date 
`endDate` date


Rooms table

`roomID`    int(11)              
`name`  varchar(255)                     
`facilities`  mediumtext

Imagine there are 5 rooms. roomIDs are 01,02,03,04 and 05. amoung these rooms, 01 is booked. checkin date is 05-11-2013 & checkout date is 10-11-2013.

And also roomID 04, booked in 08-11-2013 to 09-11-2013


If user check availability from 04-11-2013 to 10-11-2013, only room ID 02,03 and 05 should display.

How can I build a system to display result?

Can someone help me to build sql query to check availability?

  • 写回答

1条回答 默认 最新

  • dongou2019 2014-05-21 15:40
    关注

    Logic is actually pretty simple here, you don't want anything where the start and end are inside your period, or where they're at opposite sides of any point in the range you're looking for.

    SELECT
        R.roomID,
        R.name,
        R.facilities
    FROM
        -- Use the table rooms, but name it R for shorthand.
        Rooms R
    
        -- Left joins return null if there's no match, which we use in the where clause to identify these rows
        LEFT JOIN Bookings B
        -- B is bookings, R is rooms, they're aliased to make things easier
        ON B.RoomId = R.RoomId
            AND
            (
                -- As I said at the top of this answer, we want to exclude anything that matches any of 3 conditions:
                -- The start date is between the date's the room is already booked for
                @SearchCheckingStart BETWEEN B.startDate AND B.endDate
                OR
                -- The end date is in the period where the room is already booked
                @SearchCheckingEnd BETWEEN B.startDate AND B.endDate
                OR
                -- Or our date range lies between the period we're booking for
                B.startDate BETWEEN @SearchCheckingStart AND @SearchCheckingEnd
            )
    
        WHERE -- We're only interested in results where MySQL couldn't match the results earlier, this gives us the rooms that are free.
            B.RoomId IS NULL
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥15 关于超局变量获取查询的问题
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题
  • ¥30 seata使用出现报错,其他服务找不到seata