我正在尝试学习SQL,目前正在做sqlzoo上的招待所问题。我被问题13卡住了,似乎不知道该怎么解决。
问题是:免费房间?列出2016年11月25日当天的免费客房。
下面是我尝试的解决方案。它返回空房间以及以前预订但尚未退房的房间。
SELECT id
from room
WHERE id NOT IN(
SELECT room_no
FROM booking
AND occupants=0
AND '2016-11-25' NOT IN (DATE_ADD(booking_date,INTERVAL nights DAY))
数据库设计
SQL动物园问题链接
感谢您的帮助。
使用不存在
select room_no,booking_date,nights from booking b1
where not exists ( select 1 from booking b2
where b2.booking_id=b1.booking_id
and b2.room_no=b1.room_no and
(b2.booking_date<='2016-11-25'
and DATE_ADD(b2.booking_date, INTERVAL nights DAY)>='2016-11-25' )
)
您可以别名查询以获取该日期的预订,然后右键加入房间。预订中的任何NULL都是开放房间。
SELECT id
FROM
(Select * FROM booking
WHERE '2016-11-25' >= booking_date
AND '2016-11-25' <= DATEADD(DAY, nights-1,booking_date)
) AS a
RIGHT JOIN room ON (a.room_no=room.id)
WHERE booking_date IS null