Reputation: 2637
I have two associated tables (simplified schema)
mysql> describe booking;
+----------------+------------+
| Field | Type |
+----------------+------------+
| id | int(11) |
| room_id | int(11) |
| date_from | date |
| date_to | date |
+----------------+------------+
mysql> describe room;
+-------------+------------+
| Field | Type |
+-------------+------------+
| id | int(11) |
| isDouble | tinyint(1) |
+-------------+------------+
What I need to do is get all the double (isDouble = true) rooms which are not booked during specified period (date_from, date_to) of time. I would like to get the result in one query.
Thanks for help.
Upvotes: 0
Views: 483
Reputation: 146469
try:
Select Distinct id RoomId
From room r
Where isDouble = 1
And Not Exists
(Select * From booking
Where room_id = r.id
And date_from <= @EndDateRange
And date_to >= @StartDateRange)
Upvotes: 3
Reputation: 254916
SELECT *
FROM room r
WHERE r.isDouble
AND NOT EXISTS (SELECT NULL
FROM booking b
WHERE (date_from BETWEEN 'date1' AND 'date2'
OR date_to BETWEEN 'date1' AND 'date2')
AND b.room_id = r.id)
Upvotes: 1
Reputation: 13302
Try this: SELECT * FROM room WHERE isDouble = 1 AND id NOT IN (SELECT room_id FROM booking WHERE date_to BETWEEN 'date1' AND 'date2')
Upvotes: 0