Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何从第一个表中选择第二个表中不可用的时间?_Sql_Sql Server - Fatal编程技术网

Sql 如何从第一个表中选择第二个表中不可用的时间?

Sql 如何从第一个表中选择第二个表中不可用的时间?,sql,sql-server,Sql,Sql Server,我遇到了这样一个问题:如果第二个表有多行,下面的查询将返回所有字段,而不考虑其中的内容 我已经尝试过在开始时间和结束时间之间使用not,当第二个表中只有一行时,它会非常好地工作,但只要我添加另一行,它就会返回所有内容 declare @firstTable table (time time(0)) insert @firstTable(time) values ('08:30'),('09:45'),('11:00'),('12:15'),('13:30'),('14:45'),('16:00'

我遇到了这样一个问题:如果第二个表有多行,下面的查询将返回所有字段,而不考虑其中的内容

我已经尝试过在开始时间和结束时间之间使用not,当第二个表中只有一行时,它会非常好地工作,但只要我添加另一行,它就会返回所有内容

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,但它会一直返回。

我认为
不存在
满足您的要求:

select *
from @firstTable ft
where not exists (select 1
                  from @secondTable st
                  where ft.time >= st.startTime and ft.time <= st.endTime
                 );
选择*
从@firstTable ft
不存在的位置(选择1
从@secondTable st
其中ft.time>=st.startTime和ft.time