mysql - 检查日期/时间冲突 MySQL

标签 mysql

好的...所以我有一个日历,在使用 CodeIgniter 构建的自定义 PHP 应用程序中,它从 MySQL 数据库中提取其条目。在包含条目数据的表中,有 3 个字段管理日期 (start_date)、时间 (start_time) 和持续时间 (duration)的条目。现在,当最终用户将条目移至新的日期和/或时间时,系统需要检查这 3 个字段是否存在任何计划冲突。

以下是查询中使用的一些变量:

$request_entry_id // the id of the entry being moved
$request_start_date // the requested new date
$request_start_time // the requested new time
$request_duration // the duration of the entry being moved (will remain the same)
$end_time = ($request_start_time + $request_duration); // the new end time of the entry being moved

我用于检查计划冲突的查询是:

SELECT t.id
FROM TABLE t
WHERE t.start_date = '$request_start_date'
AND (j.start_time BETWEEN '$request_start_time' AND '$end_time'))
AND t.id <> $request_entry_id

上述查询将检查与请求在同一日期和时间开始的任何条目。但是,我还想以最有效的方式检查以确保新请求不在现有条目的持续时间内(这就是窍门)。有什么建议么?提前致谢!

最佳答案

先想一下不冲突的条件比较容易理解逻辑:

The new event ends before the existing one starts, or starts after the existing event ends.

如果存在冲突,我们取上面的否定:

The new event ends after the existing one starts, and starts before the existing event ends.

在 SQL 中:

SELECT t.id
FROM TABLE t
WHERE t.start_date = '$request_start_date'
AND ('$end_time' > t.start_time AND '$request_start_time' < addtime(t.start_time, t.duration))
AND t.id <> $request_entry_id

关于mysql - 检查日期/时间冲突 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15688119/

相关文章:

mysql - 使用联接进行数据库设计时的 SQL 性能考虑

java - 使用passwordField连接到mySQL

mysql - 电商订单系统 不可变订单

php - MySQL 基准测试 : 1 query returning 1000 rows VS 1000 single-row queries

mysql - 如何对一系列数据进行分组以在 GOOGLE BigQuery 中进行分类

MySQL按总重量排序结果

php - OnClick 事件并检查 MySQL 结果

c#、Mysql数据比较问题

php - 更改 mysql 中的 htmlentities

mysql - SQL Count 使用 WHERE 子句连接表