sql - 如果日期不与现有日期重叠,则将日期范围更新到日期列中

标签 sql postgresql validation datetime

答案的后续问题 here .由于我不能对答案发表评论,所以我不能直接提问。

我需要更新一行并仍然让它检查时间是否与其他条目重叠。但是,我不知道如何更改语句以排除在检查期间查看自身。

像这样的 Insert 语句

INSERT INTO table (name, starttime, endtime) 
SELECT 'test', '2016-10-12 22:00:00', '2016-10-12 23:00:00'
FROM (SELECT 1) x 
LEFT 
JOIN table y 
ON y.starttime < '2016-10-12 23:00:00' AND y.endtime > '2016-10-12 22:00:00' 
WHERE y.id is NULL LIMIT 1;           

如何修改我的 UPDATE 语句以执行相同的操作,同时从检查中排除正在更新的行?

UPDATE table SET name = 'test2', starttime = '2016-10-12 22:15:00',
endtime = '2016-10-12 23:00:00'  WHERE id = 1

id 是主键,我用它来标识行

最佳答案

您可以在insertupdate 查询中使用not exists:

insert into a_table (name, starttime, endtime) 
select 'test', '2016-10-12 22:00:00', '2016-10-12 23:00:00'
where not exists (
    select 1 from a_table
    where starttime < '2016-10-12 23:00:00' and endtime > '2016-10-12 22:00:00'
    );

update a_table 
set name = 'test2', starttime = '2016-10-12 22:15:00', endtime = '2016-10-12 23:00:00'  
where id = 1 
and not exists (
    select 1 from a_table
    where id <> 1 
    and starttime < '2016-10-12 23:00:00' and endtime > '2016-10-12 22:15:00'
    );

关于sql - 如果日期不与现有日期重叠,则将日期范围更新到日期列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40006286/

相关文章:

sql - Postgres - 关于冲突 - 如何知道是否发生了更新而不是插入

sql - 将字符串转换为数字,将 null 或空字符串解释为 0

perl - 可以在 DBI 的 selectcol_arrayref & Co. 中使用命名占位符吗?

Jquery 有助于强制文本区域的最大长度?

Mysql 按分层文本排序,但按数字排序?

MySQL - 使用 WHERE 子句进行内部连接

MySQL 查询 - 在 UPDATE 中使用 SELECT

sql - 如何在更新语句中访问整个当前记录

java - 使用 JAXB 的 JAX-WS 请求验证

javascript - 我如何验证 Mongoose 自定义验证器中的类型