我有两张桌子,这个桌子的名字是“rooms”
,另一张是“预订”
我现在加入了两个表,当我在book_form =“2016-12-30”和book_to =“2016-12-31”之间搜索时我想要值,它将返回true,因为这两个日期在“预订”中不存在表,当在book_form =“2016-12-30”和book_to =“2017-01-05”或book_form =“2017-01-03”和book_to =“2017-01-15”之间进行搜索时,它将返回false因为这个日期存在于预订表中.
这是我的查询.
select * from rooms join room_book on rooms.room_id = room_book.room_id where status = 'available' and room_book.book_from NOT BETWEEN '2016-12-30' AND room_book.book_to NOT BETWEEN '2016-12-31'
NOTE: Sorry actually the column
book_from
date is2017-01-01
in the bookings table.
最佳答案 一个简单的SQL查询应该只返回那些没有包含提供日期的预订的房间:
SELECT *
FROM rooms
LEFT JOIN room_book
ON room_book.room_id = rooms.room_id
AND 'search_date' BETWEEN room_book.book_from AND room_book.book_to
WHERE rooms.room_id IS NULL
AND rooms.status = 'available'
替换您在上面搜索search_date的日期.
通过使用LEFT JOIN,您将获得房间中的所有记录. where子句中的IS NULL测试消除了在room_book中没有匹配行的那些行.