我有四张桌子:
我正在使用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。我该怎么解决这个问题呢。
答案 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
);
注意:
join
到Department
是不必要的,因为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";