簡體   English   中英

MySQL查詢問題:類似系統的保留

[英]MySQL query question: Reservation Like System

房間可能有或沒有保留。 保留時間為(日期)至直到(日期)。 人員按日期搜索房間:from_field和till_field。 嘗試查找是否有房間。

SELECT rooms.* FROM rooms
LEFT JOIN reservations ON reservations.room_id = rooms.id
WHERE ( reservations.from > till_field OR reservations.till < from_field )

問題:如果單個預訂成功,則查詢似乎有可用的空間,即使另一個預訂占據了該位置。

如何檢索完全沒有保留的房間:

如果沒有保留,則查詢=>返回的沒有reservations行,您還必須檢查該行( reservations.room_id IS NULL ):

SELECT rooms.* FROM rooms
LEFT JOIN reservations ON reservations.room_id = rooms.id
WHERE reservations.room_id IS NULL -- if there is no reservations
      OR reservations.from > till_field
      OR reservations.till < from_field

但是要真正獲得想要的東西,您必須檢查沒有預訂的房間:

  • fromDate or tillDate between from_field and till_field
  • OR

  • fromDate < from_field and tillDate > till_field

SELECT rooms.*
  FROM rooms
 WHERE NOT EXISTS (SELECT NULL
                   FROM reservations 
                  WHERE reservations.room_id = rooms.id
                    AND ((
                          reservations.from BETWEEN from_field AND till_field
                          OR
                          reservations.till BETWEEN from_field AND till_field
                         )
                        OR
                         (
                          reservations.from < from_field
                          AND reservations.till > till_field
                         )
                        )
                  )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM