There are two tables in my database. First table is room and second table is reservation. In my room table
id room_no type rate
1 13 1b 1000
2 14 2b 2000
3 15 3b 3000
4 16 1b 1000
5 17 2b 2000
6 18 3b 3000
In my reservation table
id room_no check_in check_out
1 13 23-2-2016 24-2-2016
2 14 24-2-2016 25-2-2016
1 13 25-2-2016 26-2-2016
1 13 27-2-2016 29-2-2016
1 13 1-3-2016 2-3-2016
1 13 7-3-2016 7-3-2016
"SELECT room_no,type,rate
FROM room
WHERE room_no not in
(select IFNULL(GROUP_CONCAT(room_no),0)
FROM reservation
WHERE check_out >= '$check_in' AND check_in <= '$check_out')"
when I select a date 24-2-2016 to 27-2-2016 then it display
room_no check_in check_out
14 24-2-2016 25-2-2016
15 25-2-2016 26-2-2016
16 27-2-2016 29-2-2016
17 1-3-2016 2-3-2016
18 7-3-2016 7-3-2016
but I want all available rooms.
To get occupied rooms for the period specified, ie '2016-02-27'-'2016-02-24'
, you can use:
SELECT DISTINCT room_no
FROM reservation
WHERE check_in <= '2016-02-27' AND check_out >= '2016-02-24'
Output:
room_no
=======
13
14
To get available rooms you can use the previous query like this:
SELECT *
FROM room
WHERE room_no NOT IN (
SELECT DISTINCT room_no
FROM reservation
WHERE check_in <= '2016-02-27' AND check_out >= '2016-02-24')
Output:
id, room_no, type, rate
=======================
3, 15, 3b, 3000
4, 16, 1b, 1000
5, 17, 2b, 2000
6, 18, 3b, 3000
You should use something like this:
"SELECT room_no, type, rate
FROM room
WHERE room_no not in
(select room_no FROM reservation
WHERE ('$check_in' BETWEEN check_in AND check_out) AND ('$check_out' BETWEEN check_in AND check_out))"
I don't know if the query is correct, but you surely have to check for between. You can't just test for check_out > than date, and check_in < date. IF you have multiple reservations this will give you Errors!!
Using a LEFT JOIN
should do the trick without using a subquery.
Something like this :
SELECT
room.room_no,
room.`type`,
room.rate,
COUNT(reservation.room_no) AS countReservation
FROM
room
LEFT JOIN reservation
ON (room.room_no = reservation.room_no)
AND (check_in <= '2016-02-24' AND check_out >= '2016-01-27')
GROUP BY
room.room_no
HAVING
countReservation = 0
An other advantage in this query is the extra column countReservation
that will even tell you if you have 1 or more reservations for the for the given timeframe for each room.
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.