Assume I have two tables, one room and rented. How can I get mysql join result like the table below.
display the availability for each room_id given quantity from the first column and booked status on second table for each date given date range.
Assume I have two tables, one room and rented. How can I get mysql join result like the table below.
display the availability for each room_id given quantity from the first column and booked status on second table for each date given date range.
Firstly, make sure from
and until
are MySQL DATE
types, and not stored as strings.
If those columns are MySQL DATE
datatype, then we can do something like this:
SELECT r.id AS room_id
, r.quantity - IFNULL(SUM(IF('2012-12-01' BETWEEN v.from AND v.until, v.quantity, 0)),0) AS `1`
, r.quantity - IFNULL(SUM(IF('2012-12-02' BETWEEN v.from AND v.until, v.quantity, 0)),0) AS `2`
, r.quantity - IFNULL(SUM(IF('2012-12-03' BETWEEN v.from AND v.until, v.quantity, 0)),0) AS `3`
, ...
FROM room r
LEFT
JOIN room_reservation v
ON v.room_id = r.id
AND v.until >= '2012-12-01'
AND v.from <= '2012-12-31'
GROUP BY r.id, r.quantity
ORDER BY r.id
If those aren't DATE
datatypes, and aren't strings in canonical YYYY-MM-DD
format, then we can use the MySQL STR_TO_DATE
function to convert to DATE
. The SQL will just be a little messier.