简体   繁体   中英

mysql query comparing 2 date ranges

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 ..

This is the best explanation about overlaping data ranges

Determine Whether Two Date Ranges Overlap

SQL Fiddle Demo

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 |

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

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 .

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)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM