多个内部子查询未按预期返回

时间:2017-06-01 15:08:48

标签: c# asp.net sql-server

以下是我的SQL表:

CREATE TABLE [dbo].[My_Employee_Schedule] (
[Emp_Sch_Id]    INT      IDENTITY (1, 1) NOT NULL,
[Schedule_Date] DATETIME NULL,
[Start_Time]    DATETIME NULL,
[End_Time]      DATETIME NULL,
[Emp_ID]        INT      NULL,
[Job_ID]        INT      NULL,
PRIMARY KEY CLUSTERED ([Emp_Sch_Id] ASC),
FOREIGN KEY ([Emp_ID]) REFERENCES [dbo].[My_Employee] ([Employee_Id]) ON DELETE CASCADE,
FOREIGN KEY ([Job_ID]) REFERENCES [dbo].[My_Job_Type] ([Job_Type_Id]) ON DELETE CASCADE
);

CREATE TABLE [dbo].[My_Job_Type] (
[Job_Type_Id] INT           IDENTITY (1, 1) NOT NULL,
[Job_Title]   NVARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([Job_Type_Id] ASC)
);

我正在创建一个ASP.NET C#Web应用程序,并尝试使用以下数据执行以下操作:

  • 在外部ASP转发器中显示 Schedule_Date
  • 然后使用 Employee_Schedule 表中的FK显示 Job_Title(来自My_Job_Type表)

不是显示与以下日期相关的作业,而是显示所有作业。

这是我当前的SQL(显示"服务员","驱动程序""" Busser"):

SELECT Job_Title 
FROM My_Job_Type 
WHERE Job_Type_Id IN (
    SELECT Job_Id 
    FROM My_Employee_Schedule 
    WHERE Schedule_Date IN (
        SELECT DISTINCT CAST(Schedule_Date AS DATE) As Schedule_Date 
        FROM My_Employee_Schedule 
        WHERE Start_Time BETWEEN @startReportDate AND @endReportDate))

以下是我目前的输出: snip1

以下是当前数据:

  

Emp_Sch_Id Schedule_Date Start_Time End_Time Emp_ID Job_ID

     

1 03/06/2017 00:00:00 03/06/2017 09:00:00 03/06/2017 10:00:00 5 2

     

2 03/06/2017 00:00:00 03/06/2017 11:30:00 03/06/2017 12:30:00 6 1

     

3 03/06/2017 00:00:00 03/06/2017 14:00:00 03/06/2017 15:00:00 5 3

     

4 03/06/2017 00:00:00 03/06/2017 12:00:00 03/06/2017 13:00:00 4 2

     

5 03/06/2017 00:00:00 03/06/2017 12:15:00 03/06/2017 15:15:00 4 2

     

Job_Type_Id Job_Title

     

1名服务员

     

2名司机

     

3 Busser

1 个答案:

答案 0 :(得分:1)

从我可以收集到的内容来看,您似乎只需要select distinct t.Job_Title from My_Job_Type t inner join My_Employee_Schedule s on s.Job_ID = t.Job_Type_ID where s.Schedule_Date between @startReportDate and @endReportDate 与嵌套的不相关子查询。

regedit.exe