我目前有公交车时刻表
StopID BusID Start Stop
1 1 0400 0500
2 1 0800 0900
3 2 0600 0700
4 3 0700 0830
我希望能够将所有说BusID = 2的实例更改为与当前计划不重叠的另一个BusId。我对SQL还是很陌生,但是我可以在编写过程中得到一些建议吗?
我想更新表格,所以最终会变成
StopID BusID Start Stop
1 1 0400 0500
2 1 0800 0900
3 1 0600 0700
4 3 0700 0830
对于总线2的所有实例。
最佳答案
您可以将str_to_date(<string>,"%h%i")
函数与not exists
一起使用:
set @myBus_ID = 2;
select *
from tab t
where not exists (select 0
from tab
where Bus_ID = @myBus_ID
and str_to_date(start, "%h%i")<=str_to_date(t.stop, "%h%i")
and str_to_date(stop, "%h%i")>=str_to_date(t.start, "%h%i"))
查询针对您当前的情况返回
Bus_ID = 1
。或将
str_to_date(<string>,"%h%i")
替换为time_format(<string>,"%h%i")
作为替代功能。要更新您的时间表,可以使用:
set @myBus_ID = 2;
update tab t
join
(
select distinct Bus_ID
from tab t
where not exists (select 0
from tab
where Bus_ID=@myBus_ID
and time_format(start, "%h%i")<=time_format(t.stop, "%h%i")
and time_format(stop, "%h%i")>=time_format(t.start, "%h%i"))
) tt
set t.Bus_ID=tt.Bus_ID
where t.Bus_ID=@myBus_ID;
Demo
关于mysql - SQL:根据计划重新分配ID,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58585599/