检查 MySQL 中日期范围的重叠

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2545947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 15:40:18  来源:igfitidea点击:

Check overlap of date ranges in MySQL

mysqlrangeoverlapping-matches

提问by Pierre de LESPINAY

This table is used to store sessions (events):

该表用于存储会话(事件):

CREATE TABLE session (
  id int(11) NOT NULL AUTO_INCREMENT
, start_date date
, end_date date
);

INSERT INTO session
  (start_date, end_date)
VALUES
  ("2010-01-01", "2010-01-10")
, ("2010-01-20", "2010-01-30")
, ("2010-02-01", "2010-02-15")
;

We don't want to have conflict between ranges.
Let's say we need to insert a new session from 2010-01-05to 2010-01-25.
We would like to know the conflicting session(s).

我们不想在范围之间发生冲突。
假设我们需要从2010-01-052010-01-25插入一个新会话。
我们想知道冲突的会话。

Here is my query:

这是我的查询:

SELECT *
FROM session
WHERE "2010-01-05" BETWEEN start_date AND end_date
   OR "2010-01-25" BETWEEN start_date AND end_date
   OR "2010-01-05" >= start_date AND "2010-01-25" <= end_date
;

Here is the result:

结果如下:

+----+------------+------------+
| id | start_date | end_date   |
+----+------------+------------+
|  1 | 2010-01-01 | 2010-01-10 |
|  2 | 2010-01-20 | 2010-01-30 |
+----+------------+------------+

Is there a better way to get that?

有没有更好的方法来获得它?



fiddle

小提琴

回答by soulmerge

I had such a query with a calendar application I once wrote. I think I used something like this:

我曾经写过一个日历应用程序有这样的查询。我想我使用了这样的东西:

... WHERE new_start < existing_end
      AND new_end   > existing_start;

UPDATEThis should definitely work ((ns, ne, es, ee) = (new_start, new_end, existing_start, existing_end)):

更新这绝对有效((ns, ne, es, ee) = (new_start, new_end, existing_start, existing_end)):

  1. ns - ne - es - ee: doesn't overlap and doesn't match (because ne < es)
  2. ns - es - ne - ee: overlaps and matches
  3. es - ns - ee - ne: overlaps and matches
  4. es - ee - ns - ne: doesn't overlap and doesn't match (because ns > ee)
  5. es - ns - ne - ee: overlaps and matches
  6. ns - es - ee - ne: overlaps and matches
  1. ns - ne - es - ee:不重叠且不匹配(因为 ne < es)
  2. ns - es - ne - ee:重叠和匹配
  3. es - ns - ee - ne:重叠和匹配
  4. es - ee - ns - ne:不重叠且不匹配(因为 ns > ee)
  5. es - ns - ne - ee:重叠和匹配
  6. ns - es - ee - ne:重叠和匹配


Here is a fiddle

这是一个小提琴

回答by Lamy

SELECT * FROM tbl WHERE
existing_start BETWEEN $newStart AND $newEnd OR 
existing_end BETWEEN $newStart AND $newEnd OR
$newStart BETWEEN existing_start AND existing_end

if (!empty($result))
throw new Exception('We have overlapping')

These 3 lines of sql clauses cover the 4 cases of overlapping required.

这 3 行 sql 子句涵盖了需要重叠的 4 种情况。

回答by LordJavac

Lamy's answer is good, but you can optimize it a little more.

拉米的回答很好,但你可以再优化一下。

SELECT * FROM tbl WHERE
existing_start BETWEEN $newSTart AND $newEnd OR
$newStart BETWEEN existing_start AND existing_end

This will catch all four scenarios where the ranges overlap and exclude the two where they don't.

这将捕获范围重叠的所有四种情况,并排除它们不重叠的两种情况。

回答by Niraj Kumar

I had faced the similar problem. My problem was to stop booking between a range of blocked dates. For example booking is blocked for a property between 2nd may to 7th may. I needed to find any kind of overlapping date to detect and stop the booking. My solution is similar to LordJavac.

我遇到过类似的问题。我的问题是在一系列被阻止的日期之间停止预订。例如,预订在 5 月 2 日至 7 日之间被阻止。我需要找到任何类型的重叠日期来检测和停止预订。我的解决方案类似于 LordJavac。

SELECT * FROM ib_master_blocked_dates WHERE venue_id=$venue_id AND 
(
    (mbd_from_date BETWEEN '$from_date' AND '$to_date') 
    OR
    (mbd_to_date BETWEEN  '$from_date' AND '$to_date')
    OR
    ('$from_date' BETWEEN mbd_from_date AND mbd_to_date)
    OR      
    ('$to_date' BETWEEN mbd_from_date AND mbd_to_date)      
)
*mbd=master_blocked_dates

Let me know if it doesn't work.

如果它不起作用,请告诉我。

回答by Mackraken

Given two intervals like (s1, e1) and (s2, e2) with s1<e1 and s2<e2
You can calculate overlapping like this:

给定两个区间,如 (s1, e1) 和 (s2, e2) 与 s1<e1 和 s2<e2
您可以像这样计算重叠:

SELECT 
     s1, e1, s2, e2,
     ABS(e1-s1) as len1,
     ABS(e2-s2) as len2,
     GREATEST(LEAST(e1, e2) - GREATEST(s1, s2), 0)>0 as overlaps,
     GREATEST(LEAST(e1, e2) - GREATEST(s1, s2), 0) as overlap_length
FROM test_intervals 

Will also work if one interval is within the other one.

如果一个间隔在另一个间隔内,也将起作用。

回答by Vishal Kumar Sahu

Recently I was struggling with the same issue and came to end with this one easy step (This may not be a good approach or memory consuming)-

最近我正在为同样的问题苦苦挣扎,并以这个简单的步骤结束(这可能不是一个好方法或内存消耗)-

SELECT * FROM duty_register WHERE employee = '2' AND (
(
duty_start_date BETWEEN {$start_date} AND {$end_date}
OR
duty_end_date BETWEEN {$start_date} AND {$end_date}
)
OR
(
{$start_date} BETWEEN duty_start_date AND duty_end_date
OR
{$end_date} BETWEEN duty_start_date AND duty_end_date)
);

This helped me find the entries with overlapping date ranges.

这帮助我找到了日期范围重叠的条目。

Hope this helps someone.

希望这可以帮助某人。

回答by Hussein Akar

You can cover all date overlapping cases even when to-date in database can possibly be null as follows:

您可以涵盖所有日期重叠的情况,即使数据库中的日期可能为空,如下所示:

SELECT * FROM `tableName` t
WHERE t.`startDate` <= $toDate
AND (t.`endDate` IS NULL OR t.`endDate` >= $startDate);

This will return all records that overlaps with the new start/end dates in anyway.

这将返回与新开始/结束日期重叠的所有记录。