MySql检查日期范围是否重叠


+----+------------+---------------------+---------------------+---------+----------+
| id | percentage | from_date           | to_date             | type_id | tag      |
+----+------------+---------------------+---------------------+---------+----------+
|  1 |      10.00 | 2022-04-01 00:00:01 | 2022-04-05 23:59:59 |       1 | discount |
|  2 |      10.00 | 2022-04-06 00:00:01 | 2022-04-10 23:59:59 |       1 | uplift   |
|  3 |      10.00 | 2022-04-12 00:00:01 | 2022-04-15 23:59:59 |       1 | discount |
|  4 |      10.00 | 2022-04-20 00:00:01 | 2022-04-25 23:59:59 |       1 | uplift   |
+----+------------+---------------------+---------------------+---------+----------+

我试图在php中创建一个函数,供用户创建折扣/提价。用户可以选择开始日期和结束日期选择器。

现在,如果所选日期范围介于现有范围之间,我想限制用户创建折扣/提升。

根据上表,2022-04-01至2022-04-05、2022-04-12和2022-04-15的产品有折扣。因此,用户无法为该范围创建任何折扣/提升。

如上所述,2022-04-06至2022-04-10和2022-04-20至2022-04-25之间的价格有所上涨,用户无法为该范围创建任何折扣/上调。

SELECT * FROM `discounts` WHERE type_id = 1 AND (`from_date` <= $fromDate AND `to_date` >= $toDate);
SELECT * FROM discounts WHERE type_id = 1 AND '$fromDate' BETWEEN from_date AND to_date
SELECT * FROM discounts WHERE type_id = 1 AND '$toDate' BETWEEN from_date AND to_date

以上所有查询都有效。

但在2022-04-11 00:00:002022-04-11 23:59:592022-04-16 00:00:002022-04-19 23:59:59之间存在创建折扣/提升的窗口

有什么方法可以检查上述情况吗。

编辑

我的问题是:我如何验证用户是否将fromDate输入为2022-04-16,将toDate输入为2022-04-18,因为这是一个有效的日期范围,不属于表中的任何范围。所以用户可以创建这个范围的记录。

Yo可以这样检查:

SELECT * 
FROM `discounts` 
WHERE type_id = 1 
AND `from_date` <= $toDate AND `to_date` >= $fromDate;

对于$fromDate = '2022-04-11 00:00:00'$toDate = '2022-04-11 23:59:59',查询将不返回任何内容,这意味着此日期时间间隔可用

请参阅演示

您可以根据条件插入数据。以下查询中的CTE模拟有问题的参数源

insert into tbl(id, percentage, from_date, to_date, type_id, tag )
with params as( 
select timestamp '2022-04-16 00:00:01' fromDate, timestamp  '2022-04-18 00:00:01'  toDate
)
select 5, 11 ,fromDate, toDate, 1, 'discount'
from params p
where not exists(
select 1 
from tbl t
where type_id = 1 and p.fromDate < t.to_Date  and t.from_Date < p.toDate)

相关内容

最新更新