这是我的数据结构:
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
我需要一个sql查询,它将按日期范围连接两个表,返回以下结果:
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
可以使用普通语句完成,还是需要mysql函数? 任何想法?
ps:真正棘手的部分是每个房间有几个季节......
答案 0 :(得分:4)
这是关于重叠数据范围的最佳解释
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)
<强>输出强>
| 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 |
答案 1 :(得分:0)
选择rooms_free.id作为id_room,rooms_free.from作为room_from,rooms_free.to作为room_to,seasons.id作为season_id,seasons.name作为season_name FROM rooms_free
加入Seasons_free。from
&gt ; = seasons.from和rooms_free。to
&lt; = seasons.to
答案 2 :(得分:0)
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))
上述声明检查严格重叠。如果每个房间有多个季节,那么您可以使用group by
,having
和group_concat
。
答案 3 :(得分:-1)
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)