The idea is that entering the date of entry and date of departure; Show the available rooms by comparing with the reservation dates made.
Assuming the following tables and data:
CREATE TABLE Habitaciones (
habitacion_numero INT
);
CREATE TABLE Reservas (
habitacion INT,
inicio_fecha DATE,
fin_fecha DATE
);
INSERT INTO Habitaciones (habitacion_numero)
VALUES (1),(2),(3),(4),(5);
INSERT INTO Reservas (habitacion, inicio_fecha, fin_fecha)
VALUES (1, '2017-12-01','2017-12-13'),
(2, '2017-12-01','2017-12-10'),
(2, '2017-12-12','2017-12-14'),
(3, '2017-12-05','2017-12-08'),
(3, '2017-12-15','2017-12-16'),
(4, '2017-12-07','2017-12-11'),
(5, '2017-12-03','2017-12-05');
... if I execute the following SQL:
set @fecha1 = STR_TO_DATE('2017/12/09','%Y/%m/%d');
set @fecha2 = STR_TO_DATE('2017/12/11','%Y/%m/%d');
SELECT h.habitacion_numero,
CASE WHEN hr.habitacion_numero is null
THEN 'Disponible'
ELSE 'Reservada'
END AS 'Estado'
FROM habitaciones h
left JOIN (SELECT h1.habitacion_numero
FROM habitaciones h1
inner join reservas r
on h1.habitacion_numero=r.habitacion
WHERE @fecha BETWEEN r.inicio_fecha AND r.fin_fecha or
@fecha2 BETWEEN r.inicio_fecha AND r.fin_fecha
AND r.fin_fecha
) hr
on hr.habitacion_numero = h.habitacion_numero;
I get the following wrong result:
habitacion_numero Estado
----------------- ------
1 Reservada
2 Disponible
3 Disponible
4 Reservada
5 Disponible
The result is wrong because it is obvious that room 2 is not available with the dates of entry, for example.