2012-04-28 74 views
0

如何編寫查詢以選擇預訂數據庫中預訂的房間號爲 2012-05-1和2012-11-01的房間?正在寫入sql查詢

+1

你有什麼想法?請告訴我你的嘗試。 – 2012-04-28 07:39:08

回答

1

請嘗試以下

SELECT * from room 
WHERE (roomNo, hotelNo) not in 
(select roomNo, hotelNo 
    from booking 
    where datefrom between '2012-05-01' and '2012-11-01' 
    or dateto between '2012-05-01' and '2012-11-01' 
) 
3
select r.* from rooms r 
left outer join bookings b on b.roomno = r.roomno 
where b.dateto not between '2012-05-01' and '2012-11-01' 
and b.datefrom not between '2012-05-01' and '2012-11-01' 
or b.roomno is null 

SQLFiddle Example

+0

如果預訂期限在結束日期的開始時間,會發生什麼情況?你沒有得到誰在開始或結束日期中預訂了房間...... – aleroot 2012-04-28 07:51:08

+0

@aleroot:它的工作原理應該如此。請參閱SQLFiddle示例。 – 2012-04-28 08:16:05

+0

@juergend可能不適用於目前爲止沒有預訂的房間。 – 2012-04-28 11:02:11

2

這應該包括所有客房未在兩個給定日期間預訂:

SELECT * FROM Room r 
JOIN Booking b ON b.hotelNo = r.hotelNo AND r.roomNo = b.roomNo 
WHERE NOT ('2012-05-01' BETWEEN (b.dateFrom AND b.dateTo) 
OR '2012-11-01' BETWEEN (b.dateFrom AND b.dateTo)) 
+0

可能不適用於迄今爲止沒有預訂的房間 – 2012-04-28 11:03:13