背景:数据中包含开始时间、结束时间,对数据进行修改时,需要判断数据中是否会有时间冲突的现象(即一段时间在另一段时间中,eg:数据库中已有数据2020-04-06 00:00:00~2020-04-07 00:00:00,如果修改后的数据为2020-04-05 00:00:00~2020-04-07 00:00:00则不可以,即造成了时间冲突)
想到需要进行判断,判断时间是否会造成冲突。在进行实现的时候只想到如何在update中用判断语句来进行实现,网上查找了很多方法进行了很多尝试都没有实现。
最后反应过来可以将时间判断条件放到where条件中,才得以实现,代码如下:
update pTable
SET
(
name,level,starttime,endtime,createtime
) =
(select
#{name},#{level},
to_date(#{startTime},'yyyy-mm-dd hh24:mi:ss'),
to_date(#{endTime},'yyyy-mm-dd hh24:mi:ss'),
#{createTime}
from dual)
where id = #{id} and (select count(id) from pTable t
where t.endtime > to_date(#{startTime},'yyyy-mm-dd hh24:mi:ss') and
to_date(#{endTime},'yyyy-mm-dd hh24:mi:ss') > t.starttime and
t.list_id = #{listId} and t.del_flag = '0'
and id != #{id}
) = 0
//最后这里的即count(id)=0,如果为0,则说明数据库中不存在冲突的时间可以进行更新,若存在冲突的时间,则count(id)就不会为0,则无法进行更新。