gpt4 book ai didi

php - 如何检查表(mysql)中的时间分配重叠?

转载 作者:行者123 更新时间:2023-11-29 10:36:07 25 4
gpt4 key购买 nike

我在mysql中有一个时间分配表。在将新记录插入其中之前,我需要检查它是否与现有日期和时间段重叠。

数据库中的示例数据如下

Start Date   End Date   | Start Time | End Time
2017-01-01 | 2017-01-01 | 10:00 | 11:00
2017-01-01 | 2017-01-01 | 08:00 | 09:00
2017-01-01 | 2017-01-02 | 01:00 | 02:00

最后一条记录指的是 2017-01-01 和 2017-01-02,这两天都分配了 01:00 到 02:00 的时间。

下面是我将尝试推送的一些示例记录。预期结果如最后一列所示。我需要运行查询并确保这些记录不会在数据库中重叠。

Start Date   End Date   | Start Time  End Time
2017-01-01 | 2017-01-01 | 01:30 | 01:31 | OVERLAP
2017-01-02 | 2017-01-02 | 01:30 | 01:31 | OVERLAP
2017-01-01 | 2017-01-02 | 01:30 | 01:31 | OVERLAP
2017-01-01 | 2017-01-02 | 00:30 | 00:31 | PASS
2017-01-03 | 2017-01-03 | 00:30 | 00:31 | PASS
2016-12-30 | 2017-01-04 | 01:30 | 01:31 | OVERLAP
2016-12-30 | 2016-12-30 | 00:30 | 00:31 | PASS

我无法编写满足所有条件的查询。请帮助我查询以检查数据库中是否有重叠记录,我的输入是 $start_date、$end_date、$start_time 和 $end_time。

最佳答案

我提出了这个查询。请检查更多值。我是在MSSQL上做的,但是Mysql应该是一样的。如有任何问题请联系我。

 SELECT A.ID, A.START_DATE, A.END_DATE, A.START_TIME, A.END_TIME
, CASE WHEN B.START_DATE IS NULL THEN 'PASS' ELSE 'OVERLAP' END AS CHK
, B.START_DATE,B.END_DATE, B.START_TIME, B.END_TIME
FROM NEW_RECORDS A
LEFT JOIN EXISTING_RECORDS B ON A.START_DATE <=B.END_DATE
AND A.END_DATE>=B.START_DATE
AND A.START_TIME<=B.END_TIME
AND A.END_TIME>=B.START_TIME

输出:

+--------+-------------------------+-------------------------+------------------+------------------+---------+
| ID | START_DATE | END_DATE | START_TIME | END_TIME | CHK |
+--------+-------------------------+-------------------------+------------------+------------------+---------+
| 1 | 2017-01-01 00:00:00.000 | 2017-01-01 00:00:00.000 | 01:30:00.0000000 | 01:31:00.0000000 | OVERLAP |
| 2 | 2017-01-02 00:00:00.000 | 2017-01-02 00:00:00.000 | 01:30:00.0000000 | 01:31:00.0000000 | OVERLAP |
| 3 | 2017-01-01 00:00:00.000 | 2017-01-02 00:00:00.000 | 01:30:00.0000000 | 01:31:00.0000000 | OVERLAP |
| 4 | 2017-01-01 00:00:00.000 | 2017-01-02 00:00:00.000 | 00:30:00.0000000 | 00:31:00.0000000 | PASS |
| 5 | 2017-01-03 00:00:00.000 | 2017-01-03 00:00:00.000 | 00:30:00.0000000 | 00:31:00.0000000 | PASS |
| 6 | 2016-12-30 00:00:00.000 | 2017-01-04 00:00:00.000 | 01:30:00.0000000 | 01:31:00.0000000 | OVERLAP |
| 7 | 2016-12-30 00:00:00.000 | 2016-12-30 00:00:00.000 | 00:30:00.0000000 | 00:31:00.0000000 | PASS |
+--------+-------------------------+-------------------------+------------------+------------------+---------+

关于php - 如何检查表(mysql)中的时间分配重叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46403135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com