检查 MySQL 中日期范围的重叠

发布于 2024-08-27 11:01:06 字数 984 浏览 4 评论 0 原文

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

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")
;

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

这是我的查询:

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
;

这是结果:

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

有更好的方法吗?


小提琴

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-05 to 2010-01-25.
We would like to know the conflicting session(s).

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

冷…雨湿花 2024-09-03 11:01:06

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

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

更新这绝对应该有效 ((ns, ne, es, ee) = (new_start, new_end, Existing_start, Existing_end)):

  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:重叠并匹配

这是一个 小提琴

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;

UPDATE This should definitely work ((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

Here is a fiddle

尐籹人 2024-09-03 11:01:06
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')

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

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.

惜醉颜 2024-09-03 11:01:06

Lamy的答案很好,但是你可以再优化一下。

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

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

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.

今天小雨转甜 2024-09-03 11:01:06

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

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 

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

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

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.

是你 2024-09-03 11:01:06

我也遇到过类似的问题。我的问题是在一系列封锁日期之间停止预订。例如,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

如果不起作用请告诉我。

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.

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.

走野 2024-09-03 11:01:06

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

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

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

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.

倾城泪 2024-09-03 11:01:06

从性能角度来看,Mackraken 的上述答案更好,因为它不需要多个 OR 来评估两个日期是否重叠。很好的解决方案!

然而我发现在 MySQL 中你需要使用 DATEDIFF 而不是减号运算符 -

SELECT o.orderStart, o.orderEnd, s.startDate, s.endDate
, GREATEST(LEAST(orderEnd, endDate) - GREATEST(orderStart, startDate), 0)>0 as overlaps
, DATEDIFF(LEAST(orderEnd, endDate), GREATEST(orderStart, startDate)) as overlap_length
FROM orders o
JOIN dates s USING (customerId)
WHERE 1
AND DATEDIFF(LEAST(orderEnd, endDate),GREATEST(orderStart, startDate)) > 0;

Mackraken's answer above is better from a performance perspective as it doesn't require several OR's in order to evaluate if two dates overlap. Nice solution!

However I found that in MySQL you need to use DATEDIFF instead of the minus operator -

SELECT o.orderStart, o.orderEnd, s.startDate, s.endDate
, GREATEST(LEAST(orderEnd, endDate) - GREATEST(orderStart, startDate), 0)>0 as overlaps
, DATEDIFF(LEAST(orderEnd, endDate), GREATEST(orderStart, startDate)) as overlap_length
FROM orders o
JOIN dates s USING (customerId)
WHERE 1
AND DATEDIFF(LEAST(orderEnd, endDate),GREATEST(orderStart, startDate)) > 0;
逆光下的微笑 2024-09-03 11:01:06

最近我正在努力执行日期操作。以下 SQL 查询解决了过滤具有与日期相关的多个条件的行的问题:

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)
);

PS:这帮助我找到了具有重叠日期范围的条目,但可能不是一个好方法,因为它可能会消耗内存。

Recently I was struggling to perform operations with date. The following SQL query solved the issue to filter rows with multiple criteria related to date:

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)
);

PS: This helped me find the entries with overlapping date ranges however may not be a good approach as it may be memory consuming.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文