在mysql

时间:2016-12-30 06:48:23

标签: php mysql

我有两张桌子,这个桌子名称是“room”Table Rooms,另一张是“预订”Table Bookings

我现在加入了两个表格,当我在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'
  

注意: 很抱歉,实际上预订表中book_from列的日期为2017-01-01

2 个答案:

答案 0 :(得分:1)

select * 
from rooms 
join room_book on rooms.room_id = room_book.room_id 
where status = 'available' 
and room_book.book_from >= '2016-12-30' 
AND room_book.book_to <= '2016-12-31'

试试这样。

答案 1 :(得分:0)

简单的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中没有匹配行的那些行。