简体   繁体   中英

MySQL query booking system - remove entry if room is already booked

I have been banging my head on this (im a newbie in MySQL, be patient) for two days and i cannot get around this query i want to make... First the data:

I have two tables, one for the rooms like this:

  • table ROOMS
  • id_room | tipe_room | view_room
  • 1.1 | Single | Sea
  • 1.2 | Single | Country
  • 1.3 | Double | Sea
  • 1.4 | Double | Country
  • 1.5 | Single | Sea

  • table RESERVATIONS

  • id_reservation | client_number | n_room | check_in | check_out
  • 1 | 1 | 1.1 | 2012-02-20 | 2012-02-24

If a person wants to book a room with tipe_room=Single and view_room=Sea and check_in date=2012-02-15 and check_out date=2012-02-20 i want it to return the id_room available (1.1 and 1.5).

Now if a person wants to book a room with tipe_room=Single and view_room=Sea and check_in date=2012-02-19 and check_out date=2012-02-23 i want it to return the id_room available (only 1.5).

I have been trying around JOIN conditions but when conditions are met it excludes all rooms...

How can I do this, please?

Best Regards, Alex

This query should check for all four cases (A,B,C and D) of occupancy:

  check_in     check_out
      |=TEST=PERIOD=|

  |--A--| |--B--| |--C--|  <- check_in<period_end AND check_out>period_start
    |--------D--------|    <- check_in<period_start AND check_out>period_end

This is complete query:

SELECT `id_room` FROM `rooms` 
WHERE `tipe_room`='Single' AND `view_room`='Sea' 
AND NOT EXISTS 
(
SELECT * FROM `reservations` WHERE `n_room`=`rooms`.`id_room` 
AND ((`check_in`<'2012-02-20' AND `check_out`>'2012-02-15') 
 OR (`check_in`<'2012-02-15' AND `check_out`>'2012-02-20'))
)

Try this Query

select * from room where room.view = :view and room.type = :type
and (select count(*) from reservation r where r.room_id = room.id and 
(r.checkout > :checkin and r.checkin  < :checkout) or
(r.checkin  < :checkin and r.checkout > :checkin))  = 0

The main idea here is to select the room and then check that it is not already booked in the sub select.

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