我正在尝试根据用户给出的数据范围获得未预订的酒店房间。
我有两张表
- rooms,列room_id, roomno
- 包含reserv_id, room_id, checkindate, checkoutdate的reservation
我正在应用这个查询
$sql = "SELECT DISTINCT roomno
FROM rooms
LEFT JOIN reservation ON rooms.room_id = reservation.room_id
AND
(
(
(reservation.checkindate > '$newreservcheckin')
AND
(reservation.checkindate > '$newreservcheckout')
)
OR
(
(reservation.checkoutdate < '$newreservcheckin')
AND
(reservation.checkoutdate < '$newreservcheckout')
)
)";
$newreservcheckin和$newreservcheckout是用户
提供的日期范围。假设房间号分别为100和101目前100的预定时间为2016年9月16日至2016年9月18日2016年9月27日至9月29日,100号也被预订了101房间未被预订(也就是说在预订表中没有记录)
假设用户给出日期为2016年9月26日到2016年9月30日,查询将忽略从2016年9月27日到2016年9月29日的100号房间条目,但将显示日期为2016年9月16日到2016年9月18日的100号房间条目,并显示101个房间
如何塑造查询,使它可能不会给出相同的房间,但一个不同的日期?
您需要选择(A)未预订或(B)已预订但超出您查询范围的房间,以下查询应该有效:
select no from room r
where not exists (
select id from reservation where room_id = r.id)
union
select no from room r
where r.id not in (
select distinct room_id from reservation
where
checkindate between '2016-09-20' and '2016-09-22'
OR
checkoutdate between '2016-09-20' and '2016-09-22'
)
这里是SQL Fiddle。
您可以加入每一个与新的入住日期重叠的预订,并选择那些没有要加入的房间。在我的查询中,我希望新客人可以在之前退房的同一日期入住。如果不改变"& lt;"& lt; ="answers">"> ="。
SELECT
r.roomno
FROM
rooms r
LEFT JOIN
reservations res ON res.room_id = r.room_id
AND res.checkindate < '$newreservcheckout'
AND res.checkoutdate > '$newreservcheckin'
WHERE res.reserv_id IS NULL