【问题标题】:Prevent insertion of overlapping timestamp ranges to database防止将重叠的时间戳范围插入数据库
【发布时间】:2020-09-01 21:38:32
【问题描述】:

您好,希望有人能帮助我。

假设我的桌子上有以下内容

名称文本 无时区的 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);
}

【问题讨论】:

    标签: php postgresql datetime sql-insert check-constraints


    【解决方案1】:

    让数据库完成繁重的工作!您可以使用timestamp rangesan exclusion constraint 来防止插入重叠的日期范围:

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

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

    默认情况下,时间戳范围包括下限和不包括上限 - 但这可以修改。

    【讨论】:

    • 它可以工作,但如果我必须为不同的名称添加另一个时间表,它会给我一个错误。如果我为下一个用户添加 (tommy 2019-07-10 08:30:00 2019-07-10 10:30:00) 的示例,如果我添加 (john 2019-07-10 08:30:00 2019) -07-10 10:30:00) 仅当 John 的时间从 10:30:00 开始时才有效。我怎样才能让它工作?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多