2016-10-12 67 views
1

后续问题回答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是主键,我用它来识别该行

+0

?你们都有标签。 – Nicarus

+0

对不起,postgreSQL – Chanpuru

回答

1

中都可以insertupdate查询使用not exists:你使用MySQL或PostgreSQL

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' 
    ); 
+0

两个工作完美无瑕!谢谢你的帮助。 SQL语法对我来说是比较新的。 – Chanpuru