Check overlap of date ranges in MySQL(检查 MySQL 中日期范围的重叠)
问题描述
此表用于存储会话(事件):
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")
;
我们不想在范围之间发生冲突.
假设我们需要插入一个从 2010-01-05 到 2010-01-25 的新会话.
我们想知道冲突的会话.
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).
这是我的查询:
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 |
+----+------------+------------+
有没有更好的方法来获得它?
Is there a better way to get that?
小提琴
推荐答案
我曾经在一个日历应用程序中遇到过这样的问题.我想我使用了这样的东西:
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 这绝对有效((ns, ne, es, ee) = (new_start, new_end, existing_start, existing_end)):
UPDATE This should definitely work ((ns, ne, es, ee) = (new_start, new_end, existing_start, existing_end)):
- ns - ne - es - ee:不重叠且不匹配(因为 ne
- ns - es - ne - ee:重叠和匹配
- es - ns - ee - ne:重叠和匹配
- es - ee - ns - ne:不重叠且不匹配(因为 ns > ee)
- es - ns - ne - ee:重叠和匹配
- ns - es - ee - ne:重叠和匹配
<小时>
这是一个小提琴
这篇关于检查 MySQL 中日期范围的重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检查 MySQL 中日期范围的重叠


基础教程推荐
- SQL Server 2016更改对象所有者 2022-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01