简体   繁体   English

查找给定的日期范围是否在MySQL的另一个日期范围内

[英]Find if given date range inside another date range in MySQL

I have a price_table, that has two columns: start_date and end_date (for promotional prices). 我有一个price_table,其中有两列:start_date和end_date(用于促销价格)。

I'm trying to create a query that will check whether or not the given date range doesn't fall under another one that already exists. 我正在尝试创建一个查询,该查询将检查给定的日期范围是否不属于另一个已经存在的日期范围。

I've been trying to use this query: 我一直在尝试使用以下查询:

SELECT *
FROM tbl_preco
WHERE isActive = 1 AND (start_date between '2014-12-11 15:45:00' AND '2014-12-13 11:45:00'
        OR end_date between '2014-12-11 15:45:00' AND '2014-12-13 11:45:00')

The problem is: 问题是:

There's a promotional price from 2014-12-10 15:30:00 to 2014-12-13 14:30:00 , so neither of both BETWEEN instructions are catching it, even though the given range is in fact inside the range in the DB. 2014-12-10 15:30:002014-12-13 14:30:00有促销价格,因此即使指定的范围实际上在D B。

                   |------GIVEN RANGE-------|
       |-------- RANGE IN DB --------|

The example above should be returned as TRUE, and the application will tell the user that there's already a promotional price within the given range. 上面的示例应返回为TRUE,应用程序将告诉用户在给定范围内已经有促销价格。

It sounds like you want any promotional sale that is active during the range. 听起来您想在此范围内进行任何促销销售。 In that case, you don't need to check that the start dates and end dates exist in the range, which is what you are doing now. 在这种情况下,您无需检查范围中是否存在开始日期和结束日期,这就是您正在执行的操作。 You simply need to check that the start date happened before the range is closed, and then that the end date happened after the range opened. 您只需要检查开始日期是否在范围关闭之前发生,然后检查结束日期是否在范围打开之后发生。 Hope that makes sense? 希望这有意义吗?

SELECT *
FROM tbl_preco
WHERE isActive = 1 
AND start_date < '2014-12-13 11:45:00' 
AND end_date > '2014-12-11 15:45:00';

A simple condition to find out if two segments [a, b] and [c, d] intersect each other is (ad)*(bc) <= 0 . 找出两个段[a,b]和[c,d]是否相交的简单条件是(ad)*(bc) <= 0 It covers all the situations, when one date range (segment) only starts or only ends during the other and also when one of the is completely included into the other. 它涵盖了所有情况,当一个日期范围(段)仅在另一日期范围内开始或仅在另一日期范围内结束时,以及其中一个日期范围完全包含在另一个日期范围内时。

In order to implement this in MySQL using dates you need to convert them to numbers (Unix timestamps): 为了使用日期在MySQL中实现此功能,您需要将它们转换为数字(Unix时间戳):

SELECT *
FROM tbl_preco
WHERE isActive = 1
   AND (UNIX_TIMESTAMP(start_date) - UNIX_TIMESTAMP('2014-12-11 15:45:00'))
     * (UNIX_TIMESTAMP(end_date) - UNIX_TIMESTAMP('2014-12-13 11:45:00')) <= 0
;

When the product is 0 the date ranges either one is included into the other (start together or end together) or one of them starts exactly when the other ends. 当乘积为0时,日期范围之一将包含在另一个范围内(一起开始或一起结束),或者其中一个恰好在另一个结束时开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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