查询#2给大家一个给定的hotel_id
和check in
/check out
日的免费客房(该in
和out
日期都包括在内,对于05/n到10/n,你留6天)
查询#3会给你所有租用的房间与以前的参数。
SQL Fiddle
的MySQL 5.6架构设置:
CREATE TABLE TblReservation
(`reservation_id` int, `hotel_id` int, `room_id` int, `check_in` date, `check_out` date)
;
INSERT INTO TblReservation
(`reservation_id`, `hotel_id`, `room_id`, `check_in`, `check_out`)
VALUES
(1, 1, 1, '2017-04-01', '2017-04-02'),
(2, 1, 1, '2017-04-06', '2017-04-10'),
(3, 1, 2, '2017-04-01', '2017-04-03'),
(4, 1, 4, '2017-04-01', '2017-04-10'),
(5, 2, 5, '2017-04-01', '2017-04-10')
;
CREATE TABLE TblRoom
(`room_id` int, `hotel_id` int, `room_num` int)
;
INSERT INTO TblRoom
(`room_id`, `hotel_id`, `room_num`)
VALUES
(1, 1, 1100),
(2, 1, 1200),
(3, 1, 1300),
(4, 1, 1400),
(5, 2, 2500)
;
查询1:
set @hotel_id = 1, @check_in = '2017-04-03', @check_out = '2017-04-05'
查询2:
select TblRoom.*
from TblRoom
left join TblReservation
on TblRoom.hotel_id = TblReservation.hotel_id
and TblRoom.room_id = TblReservation.room_id
and TblReservation.check_out >= @check_in
and TblReservation.check_in <= @check_out
where
TblRoom.hotel_id = @hotel_id
and TblReservation.reservation_id IS NULL
Results:
| room_id | hotel_id | room_num |
|---------|----------|----------|
| 1 | 1 | 1100 |
| 3 | 1 | 1300 |
查询3:
select
TblRoom.*,
date_format(check_in,'%Y-%m-%d') check_in,
date_format(check_out,'%Y-%m-%d') check_out
from TblRoom
inner join TblReservation
on TblRoom.hotel_id = TblReservation.hotel_id
and TblRoom.room_id = TblReservation.room_id
and TblReservation.check_out >= @check_in
and TblReservation.check_in <= @check_out
where
TblRoom.hotel_id = @hotel_id
Results:
| room_id | hotel_id | room_num | check_in | check_out |
|---------|----------|----------|------------|------------|
| 2 | 1 | 1200 | 2017-04-01 | 2017-04-03 |
| 4 | 1 | 1400 | 2017-04-01 | 2017-04-10 |
请给我们一个数据样本来测试。 – Blag
请给我们一个你想要的输出样本。 –
我下载了你的样本数据库。如果你提供样本数据,我可能会给你你需要的查询。 –