防止在数据库中插入重叠的时间戳范围



嗨,我希望有人能帮助我。

假设我的桌子上有以下

名称文本startTime时间戳(不带时区(endTime时间戳,不带时区

我想做的是:

我正在尝试检查即将添加到数据库中的时间是否会与表上已经存在的时间重叠。

示例:

name            startTime               endTime
---------|------------------------|----------------------
tommy    |   2019-07-10 08:30:00  |   2019-07-10 10:30:00
tommy    |   2019-07-10 10:31:00  |   2019-07-10 11:30:00  
tommy    |   2019-07-10 07:30:00  |   2019-07-10 09:00:00 <=== if I click enter to enter this tird schedulle for this user, the sistem will give me a conflict message because this user already has a schedulle that start from 2019-07-10 08:30:00 to 2019-07-10 10:30:00 on our first row of the table.

至于我要插入数据库的代码,我只有这个简单的php

$sql = "insert into horarios (name, startTime, endTime) values ('$name', '$startTime', '$endTime');";
$res = @pg_query ($con, $sql);
if ($res == NULL){
echo "Query failed.";
exit (0);
}

让数据库来承担重任!您可以使用时间戳范围和排除约束来防止插入重叠的日期范围:

alter table horarios
add constraint horarios_range_overlap
exclude using gist (tsrange(startTime, endTime) with &&)

数据库使用时间戳作为边界来构建tsrange,然后使用运算符&&确保没有重叠。冲突记录被拒绝。

默认情况下,时间戳范围在下限是包含的,在上限是互斥的,但这是可以修改的。

最新更新