![](/img/trans.png)
[英]PHP/SQL - How can I check if a date user input is in between an existing date range in my database?
[英]How to return IDs ONLY of Properties that do not have existing booking from date range input by user?
我正在假期出租多功能网站上进行属性搜索。 搜索采用到达日期和离开日期的参数。 这些属性有多个重复的日期,因为允许它们为每个属性导入多个文档以整合预订。 如何编写一个查询,该查询仅返回不具有参考用户输入的现有预订日期的属性ID?
本质上,我想从用户输入中返回日期范围内所有可用的属性。
试过这个。
SELECT p.name
FROM property AS p
INNER JOIN property_calendar AS pc
ON p.id = pc.property_id
WHERE COALESCE('2018-11-17' NOT BETWEEN pc.start AND pc.end, TRUE)
AND COALESCE('2018-11-19' NOT BETWEEN pc.start AND pc.end, TRUE)
数据库表:(仅显示相关列)
属性
id | name
-------------------------------------
1 | Beaches & Flows
2 | Mo Beaches Mo Problems
3 | 99 Problems and they all Beaches
property_calendar
id | property_id | start (Y-m-d) | end (Y-m-d)
----------------------------------------------
1 | 1 | 2019-3-13 | 2019-3-17
2 | 1 | 2019-4-13 | 2019-4-17
3 | 1 | 2019-3-13 | 2019-3-17
4 | 1 | 2019-3-13 | 2019-3-17
5 | 2 | 2019-3-13 | 2019-3-17
6 | 3 | 2019-5-13 | 2019-5-17
7 | 3 | 2019-6-13 | 2019-6-17
8 | 3 | 2019-7-13 | 2019-7-17
尽管日历表上每个属性都有重复的日期,但我只希望它在该日期范围内可用时仅返回一次属性ID。 如果有任何出现的日期都不可用于属性,则查询中不应返回任何内容。
我真的非常感谢我能获得的任何帮助!
检查是否存在与NOT EXISTS子查询重叠的日期范围:
set @new_start = '2019-06-16';
set @new_end = '2019-06-19';
select *
from property p
where not exists (
select *
from property_calendar c
where c.property_id = p.id
and c.start < @new_end
and c.end > @new_start
)
结果:
id | name
---|-----------------------
1 | Beaches & Flows
2 | Mo Beaches Mo Problems
属性3被排除在外,因为范围(2019-6-13、2019-6-17)与(2019-06-16、2019-06-19)重叠。
根据是否要在一天内重叠,您可能需要将<
和>
更改为<=
和>=
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.