Fuxi
Fuxi

Reputation: 7589

MySQL querying date range

Here's my database (free rooms in a hotel, simplified)

rooms_available:

id  date_available   room_id
================================
1   2013-12-19       2
2   2013-12-20       2
3   2013-12-21       2
4   2013-12-22       2
5   2013-12-23       2
6   2013-12-25       3

rooms:

id  name           minimal_range
================================
2   Apartment A    5
3   Apartment B    1

I want to query all rooms which are available between 2013-12-20 and 2013-12-22

My query is like:

select * 
from rooms_available 
where (date='2013-12-20' OR date='2013-12-21' OR date='2013-12-22')

My questions:

Thanks

Upvotes: 0

Views: 76

Answers (3)

Akhil Sidharth
Akhil Sidharth

Reputation: 746

SELECT * FROM rooms_available WHERE `date_available` BETWEEN "2013-12-20 " AND "2012-03-31"

Upvotes: 1

adamS
adamS

Reputation: 600

I didn't test this but it should point you in the right direction especially for the second part of your question about minimal range.

SELECT t1.id as id, t1.date_available as date_available, t1.room_id 
FROM rooms_availble as t1 JOIN rooms as t2 on t1.room_id = t2.id 
WHERE t1.date_available BETWEEN DATE('2013-12-20') AND DATE('2012-03-31') AND
t2.minimal_range <= datediff('2013-12-22', '2012-12-20');

The mysql datediff function will return the number of days between two dates then you can just compare it with the minimal_range from the rooms join table. Also you might consider binding the start and end dates to variables so that you only have to write each date once.

Upvotes: 0

Scott Hunter
Scott Hunter

Reputation: 49803

date >= '2013-12-20' and date <= '2013-12-22'

Upvotes: 1

Related Questions