Reputation: 7599
here's my data structure:
seasons
id from to name
----------------------------------------
1 2015-11-01 2015-12-15 season1
2 2015-12-16 2015-12-30 season2
3 2015-12-31 2016-01-20 season3
rooms_free
id from to room_id
----------------------------------------
1 2015-11-26 2015-11-30 1
2 2015-12-19 2015-12-28 2
3 2015-12-22 2015-12-29 3
i need an sql query which will join both tables by date range returning the following result:
id_room room_from room_to season_id season_name
-------------------------------------------------------------
1 2015-11-26 2015-11-30 1 season1
2 2015-12-19 2015-12-28 2 season2
3 2015-12-22 2015-12-29 2 season2
could this be done using normal statements or would i need a mysql function? any ideas?
ps: the really tricky part is when there's several seasons per room ..
Upvotes: 0
Views: 74
Reputation: 48197
This is the best explanation about overlaping data ranges
Determine Whether Two Date Ranges Overlap
SELECT rf.room_id as id_room ,
rf.from as room_from,
rf.to as room_to,
s.id as season_id,
s.name as season_name
FROM rooms_free rf
JOIN seasons s
ON (rf.From <= s.to) and (rf.to >= s.from)
OUTPUT
| room_id | from | to | id | name |
|---------|----------------------------|----------------------------|----|---------|
| 1 | November, 26 2015 00:00:00 | November, 30 2015 00:00:00 | 1 | season1 |
| 2 | December, 19 2015 00:00:00 | December, 28 2015 00:00:00 | 2 | season2 |
| 3 | December, 22 2015 00:00:00 | December, 29 2015 00:00:00 | 2 | season2 |
Upvotes: 4
Reputation: 1
SELECT rooms_free.id as id_room, rooms_free.from as room_from , rooms_free.to as room_to, seasons.id as season_id, seasons.name as season_name FROM rooms_free
join seasons on rooms_free.from
>=seasons.from and rooms_free.to
<=seasons.to
Upvotes: 0
Reputation: 76551
select rooms_free.id as id_room, rooms_free.from as room_from, rooms_free.to as room_to, seasons.id as season_id, seasons.name as season_name
from rooms_free
join seasons
on ((rooms.from <= seasons.from) and (seasons.from <= rooms.to)) or ((seasons.from <= rooms.from) and (rooms.from <= seasons.to))
The statement above checks for strict overlapping. If there are several seasons per room, then you can use group by
, having
and group_concat
.
Upvotes: 0
Reputation: 7023
Select rooms_free.id, rooms_free.from, rooms_free.to, seasons.id, seasons.name
from rooms_free , seasons
where (rooms_free.from >= season.from and rooms_free.to <= seasons.to)
Upvotes: -1