[英]Select specific records between two dateranges
我試圖根據用戶給定的日期范圍獲取未預訂的酒店房間。
我有兩張桌子
我正在應用此查詢
$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的房間,現在從2016年9月16日至2016年9月18日預訂了100個房間,從2016年9月27日至2016年9月29日也預訂了100個房間,沒有預訂101號房間(表示預訂表中沒有記錄)
假設用戶輸入的日期為2016年9月26日至2016年9月30日,查詢將忽略房間號為100的條目,該條目的日期為2016年9月27日至2016年9月29日,但顯示的房間號為100,日期為9- 2016年16月16日至2016年9月18日,將顯示101間客房
如何塑造查詢,使其可能不會提供相同的房間,而是提供不同的日期?
您可以加入與新的檢查日期重疊的所有預訂,然后選擇沒有任何客房的房間。 在我的查詢中,我希望新來賓可以在先前退房的同一天入住。 如果不是,則將“ <”更改為“ <=“,將”>”更改為“> =”。
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
您需要選擇(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 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.