SQL查询从四个表中检索不同的记录

时间:2016-05-10 10:42:38

标签: sql sql-server

我有四张桌子:

  • 部门(DepartmentId)
  • 课程(CourseId,DepartmentId)
  • CourseInstructor(CourseId,InstructorId)
  • 讲师(InstructorId,FirstName,LastName,HireDate)

我正在使用asp.net mvc。教师模型是 -

public class Instructor
{
  public int InstructorId {get; set;}
  public string FristName {get; set;}
  public string LastName {get; set;}
  public DateTime HireDate {get; set;}
  public string FullName 
  {
     get 
     {
       return FirstName + " " + LastName;
     } 
  }

现在我需要根据给定的DepartmentId查找部门的所有不同教师记录。

我编写了以下sql查询,但它说 -

  

不明确的专栏名称' InstructorId'

string query = "select InstructorId, MAX(FirstName), MAX(LastName) from Instructor "
            + "left join CourseInstructor on CourseInstructor.InstructorId = Instructor.InstructorId "
            + "left join Course on Course.CourseId = CourseInstructor.CourseId "
            + "left join Department on Department.DepartmentId=Course.DepartmentId "
            + "where Department.DepartmentId=@p0 "
            + "group by Instructor.InstructorId";
        IEnumarable<Instructor> Instructors = db.Database.SqlQuery<Instructor>(query, id);

这里的id是给定的DepartmentId。我该怎么解决这个问题呢。

4 个答案:

答案 0 :(得分:1)

使用聚合是可疑的。以下是使用exists的替代方法:

select i.*
from Instructor i
where exists (select 1
              from CourseInstructor ci join 
                   Course c
                   on c.CourseId = ci.CourseId 
              where ci.InstructorId = i.InstructorId and
                    c.DepartmentId = @p0
             );

注意:

  • 此版本不需要聚合,因此它应该更快。
  • joinDepartment是不必要的,因为ID在Course表中。
  • left join是不必要的,因为您的查询需要DepartmentId上的匹配。
  • 表别名使查询更易于编写和阅读。
  • 完全限定的列名可以防止出现问题。

答案 1 :(得分:0)

因为InstructorId出现在多个表中,SQL Server不知道要返回哪个表。有两种方法可以解决这个问题。

您可以将表名附加在列名前面。因此SELECT InstructorId...变为SELECT Instructor.InstructorId...

或者,您可以减少aliasing表格的输入量,并在列名称前附加别名。

select 
    i.InstructorId, 
    MAX(i.FirstName), 
    MAX(i.LastName) 
from 
    Instructor AS i
         left outer join CourseInstructor AS ci         on ci.InstructorId  = i.InstructorId 
         left outer join Course on AS c                 on c.CourseId       = ci.CourseId 
         left outer join Department AS d                on d.DepartmentId   = c.DepartmentId 
where 
    d.DepartmentId=@p0 
group by 
    i.InstructorId
;

答案 2 :(得分:0)

您需要限定两个或多个所选表中存在的所有列名:

LOCK_NB

答案 3 :(得分:0)

使用以下查询

string query = "select Instructor.InstructorId, MAX(FirstName), MAX(LastName) from Instructor "
        + "left join CourseInstructor on CourseInstructor.InstructorId = Instructor.InstructorId "
        + "left join Course on Course.CourseId = CourseInstructor.CourseId "
        + "left join Department on Department.DepartmentId=Course.DepartmentId "
        + "where Department.DepartmentId=@p0 "
        + "group by Instructor.InstructorId";