mysql查询用于获取未在预期结果的日期范围之间预订的所有房间

时间:2015-08-21 14:08:20

标签: mysql sql group-by left-join

我正在创建一个预订系统,它有2个表

房间

#!/bin/bash


expandTilde()
{
    local tilde_re='^(~[A-Za-z0-9_.-]*)(.*)'
    local path="$*"
    local pathSuffix=

    if [[ $path =~ $tilde_re ]]
    then
        # only use eval on the ~username portion !
        path=$(eval echo ${BASH_REMATCH[1]})
        pathSuffix=${BASH_REMATCH[2]}
    fi

    echo "${path}${pathSuffix}"
}



result=$(expandTilde "$1")

echo "Result = $result"

预订

id  | name          | no_of_rooms   
1   | Lake View     | 4
2   | Royale        | 2
3   | Sky View      | 6

在搜索页面上创建新预订时,我想找到此日期范围内可用的空房

搜索价值 开始时间:2015-08-11 结束时间:2015-08-12

预期结果

id |room_id     | start             | end           | total_rooms
4  |1           | 2015-08-13        | 2015-08-14    | 2
5  |2           | 2015-08-20        | 2015-08-22    | 1
6  |2           | 2015-08-01        | 2015-08-13    | 1

结果我得到了

id | name       | no_of_rooms       | available_rooms
1  | Lake View  | 4                 | 4
2  | Royale     | 2                 | 1
3  | Sky View   | 6                 | 6

这是我为房间可用性编写的代码

id  | name          | no_of_rooms   | available_rooms
1   | Lake View     | 4             | 0
2   | Royale        | 2             | 1
3   | Skyview       | 6             | 0

我也不希望显示无法使用的房间。无论我尝试了什么,结果都是完全错误的。希望你们能帮助我!

1 个答案:

答案 0 :(得分:3)

您可以尝试:

SELECT r.id AS roomID, r.name, r.no_of_rooms, 
       r.no_of_rooms - COALESCE(t.bookedRooms,0) AS available_rooms
FROM rooms AS r
LEFT JOIN (
   SELECT room_id, SUM(total_rooms) AS bookedRooms
   FROM bookings
   WHERE `start` < '2015-08-14' AND `end` > '2015-08-11'
   GROUP BY room_id ) AS t
ON r.id = t.room_id
WHERE r.no_of_rooms - COALESCE(t.bookedRooms,0) > 0

查找指定期间预订房间的关键是以下谓词:

`start` <= '2015-08-12' AND `end` >= '2015-08-11'

以上所有房间的预订期重叠,即使是一天,也会指定期间。

GROUP BY上使用room_id,我们可以在指定的时间内获得room_id个预订房间的总和

要获得预期的结果集,我们可以使用已预订聚合的派生表执行LEFT JOIN,只需从可用房间数中减去预订房间的总和。

Demo here