我遇到的问题是,如果第二个表有多行,则下面的查询将返回所有字段,无论其中有什么内容。
我已经尝试过不在开始时间和结束时间之间使用,当第二个表中只有一行时,但是一旦我添加另一行,它就会返回所有内容。
declare @firstTable table (time time(0))
insert @firstTable(time) values ('08:30'),('09:45'),('11:00'),('12:15'),('13:30'),('14:45'),('16:00'),('17:15'),('18:30')
declare @secondTable table (startTime time(0), endTime time(0))
insert @secondTable(startTime, endTime) values ('08:30','10:45'),('13:30','17:00')
select distinct f.time
from @firstTable f, @secondTable s
where f.time not between s.startTime and s.endTime
使用上面的代码,预期的解决方案应该是11:00、12:15、17:15和18:30,但它会始终返回。
答案 0 :(得分:2)
我认为not exists
是您想要的:
select *
from @firstTable ft
where not exists (select 1
from @secondTable st
where ft.time >= st.startTime and ft.time <= st.endTime
);
Here是db <>小提琴。