SQL 结合多个时间表可用性和限制信息

SQL combining multiple schedule availability and limitation information

我正在 SQL Server 2016 中开发一个预订应用程序,其中主要 table 有可以为每个员工预订的时间段。还有多个其他 table 提供有关是否可以进行预订的信息(肯定或否定)。例如,可以有员工可用性 table(正数)显示何时可以预订员工,以及假期 table 显示何时无法预订员工。

主要table:

CREATE TABLE [tbl_timeslots]
(
    [slotid] [int] ,
    [fromdate] [datetime] ,
    [todate] [datetime] ,
    [staffid] [int] 
)

积极 table(有工作人员时)

CREATE TABLE [tbl_availability]
(
    [staffid] [int] ,
    [fromdate] [datetime] ,
    [todate] [datetime] 
) 

否定table(没有工作人员时)

CREATE TABLE [tbl_holidays]
(
    [staffid] [int] ,
    [fromdate] [datetime] ,
    [todate] [datetime] 
) 

任务:从主要 table 中找到所有工作人员有空且不在假期的时间段。

我正在寻找一种方法来组合这些多个 positive/negative table 以确定特定员工在特定 start/end 期间是否可用。

我知道这可以像下面的例子一样使用 EXISTS / NOT EXISTS 来完成,但问题是一旦你必须迭代大量可用选项和几个 positive/negative tables 这变得非常慢。

select 
    staffid, fromdate, todate 
from 
    tbl_timeslots 
where 
    exists (select staffid from tbl_availability 
            where tbl_availability.staffid = tbl_timeslots.staffid 
              and tbl_availability.fromdate <= tbl_timeslots.fromdate 
              and tbl_availability.todate >= tbl_timeslots.todate) 
    and not exists (select tbl_holidays.staffid from tbl_holidays 
                    where tbl_holidays.staffid = tbl_timeslots.staffid 
                      and tbl_holidays.fromdate < tbl_timeslots.todate 
                      and tbl_holidays.todate > tbl_timeslots.fromdate)

我的问题是是否有更好的方法 tm combine/merge 所有这些 positive/negative table 使用 SQL 生成一个输出 table 显示可用性。

您可以按如下方式使用left join

select distinct staffid, fromdate,todate 
  from tbl_timeslots t
Left join tbl_availability a
       On A.staffid=t.staffid and a.fromdate<=t.fromdate and a.todate>=t.todate
Left join tbl_holidays h
       On h.staffid=t.staffid and h.fromdate<t.todate and h.todate >t.fromdate
Where h.staffid is null and a.staffid is not null