有可能有或没有预订的房间。预订从(日期)到(日期)。人员按日期搜索房间:from_field和till_field。试着找一个房间是否可用。
SELECT rooms.* FROM rooms
LEFT JOIN reservations ON reservations.room_id = rooms.id
WHERE ( reservations.from > till_field OR reservations.till < from_field )
问题:如果单个预订成功,则查询似乎具有可用空间,即使另一个预留占据该位置。
答案 0 :(得分:3)
如何检索没有重新开始的房间:
如果没有预订,查询将返回reservations
行=&gt;您还必须检查(reservations.room_id IS NULL
):
SELECT rooms.* FROM rooms
LEFT JOIN reservations ON reservations.room_id = rooms.id
WHERE reservations.room_id IS NULL -- if there is no reservations
OR reservations.from > till_field
OR reservations.till < from_field
但要真正得到你想要的东西,你必须检查没有任何预订的房间:
<子>
子>
fromDate or tillDate between from_field and till_field
OR
fromDate < from_field and tillDate > till_field
SELECT rooms.*
FROM rooms
WHERE NOT EXISTS (SELECT NULL
FROM reservations
WHERE reservations.room_id = rooms.id
AND ((
reservations.from BETWEEN from_field AND till_field
OR
reservations.till BETWEEN from_field AND till_field
)
OR
(
reservations.from < from_field
AND reservations.till > till_field
)
)
)