简体   繁体   中英

mysql check next and previous available period in room availability query

for a project of mine I would like to add the feature to show the previous and the next available period in a booking reservation system.

I have this query that checks if the house is available:

SELECT id
  FROM tbl_reservations
  WHERE (
    `status` LIKE 'confirmed' OR `status` LIKE 'total-payed'
   ) AND (
     '2015-08-12' BETWEEN checkin AND checkout 
     OR checkout BETWEEN '2015-08-12' AND '2015-08-13'
     OR '2015-08-12' BETWEEN checkin AND checkout
     OR checkin BETWEEN '2015-08-12' AND '2015-08-13'
   );

If it finds a reservation in that period, the PHP script return false, so it shows a message like

"Sorry, no availability in that selected period"

I would like to show also something like:

"The next available period for a stay of XX nights is: "

and then show the checkin and the checkout date.

Same thing for the previous period .

I am not mastering sql 100%, so I am here asking for suggestions of any kind to point me in the right direction.

Here are the two solutions.

Get next available reservation for the expected stay:

SELECT id
FROM tbl_reservations
WHERE (
  `status` != 'confirmed' and `status` != 'total-payed'
 )
and checkin = (select min(checkin) from tbl_reservations
               where checkin > '2015-08-12'
                 and checkout - checkin >= '2015-08-12' - '2015-08-13');          

Get previous reservation for the expected stay.

SELECT id
  FROM tbl_reservations
  WHERE (
    `status` != 'confirmed' and `status` != 'total-payed'
   )
  and checkin = (select max(checkin) from tbl_reservations
                 where checkin < '2015-08-12'
                 and checkout - checkin >= '2015-08-12' - '2015-08-13');

These can easily be combined into one query, but from the question it looked like you wanted two separate queries. These are tested and ready to go..

I have solved this way:

As a visitor is interested mainly in the period he/she has selected, I run the same query for a maximun of 30days before and 30days after the original checkin date.

I break the loop as soon as I get a "false", that means NO RESERVATIONS in theat period.

Maybe it is not the most elegant way or the most performant, but it's working and I am happy :)

Any further suggestion is still accepted. Bettering, always!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM