答案的后续问题 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 是主键,我用它来标识行
最佳答案
您可以在insert
和update
查询中使用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/