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

时间:2017-09-25 10:36:11

标签: php mysql sql

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

db中的示例数据如下

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均在两天内分配。

以下是我将尝试推送的一些示例记录。预期结果显示为最后一列。 我需要运行查询并确保这些记录不会在db中重叠。

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

我无法编写满足所有条件的查询。 请帮我查询db中的重叠记录,我的输入是$ start_date,$ end_date,$ start_time和$ end_time。

1 个答案:

答案 0 :(得分:1)

我做了这个查询。请检查更多值。我是在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    |
+--------+-------------------------+-------------------------+------------------+------------------+---------+