我试图从表中的一个表中获取一个额外的列,其中一个表位于左外连接中,
PFB我的表,
Create table tblEmployee(
ID int identity primary key,
FirstName nvarchar(50),
LastName nvarchar(50),
Gender nvarchar(50),
Salary int
)
Create table tblCourses(
CourseId int identity primary key,
CourseName nvarchar(50) not null
)
Create table tblEmpCourses(
EmpCourseSlNo int identity primary key,
EmpID int foreign key references tblEmployee(ID),
CourseID int foreign key references tblCourses(CourseId)
)
PFB插入语句,
insert into tblEmployee values ('FName1', 'LName1', 'Male', '10000')
insert into tblEmployee values ('FName2', 'LName2', 'Male', '15000')
insert into tblEmployee values ('FName3', 'LName3', 'Female', '30000')
insert into tblEmployee values ('FName4', 'LName4', 'Male', '50000')
insert into tblEmployee values ('FName5', 'LName5', 'Male', '60000')
insert into tblEmployee values ('FName6', 'LName6', 'Female', '0000')
insert into tblEmployee values ('FName7', 'LName7', 'Male', '10000')
insert into tblEmployee values ('FName8', 'LName8', 'Male', '30000')
insert into tblCourses values ('Asp.net')
insert into tblCourses values ('C#')
insert into tblCourses values ('WebAPI')
insert into tblCourses values ('SQL')
insert into tblCourses values ('WCF')
insert into tblCourses values ('JS')
insert into tblCourses values ('CSS')
insert into tblCourses values ('JAVA')
insert into tblEmpCourses values (1, 1)
insert into tblEmpCourses values (1, 2)
insert into tblEmpCourses values (1, 3)
insert into tblEmpCourses values (1, 4)
如何编写查询以使用所有员工firstName获取数据,其中他已经订阅了任何课程,或者没有订阅courseID和courseName
尝试使用以下查询,但无法在select语句中添加CourseName,如何在此添加一个连接b / w tblEmpCourses表和使用left_outer_join的tblCourses以获取CourseName
所以我希望数据为
select FirstName, CourseID
from tblEmployee
left outer join tblEmpCourses
on tblEmployee.ID = tblEmpCourses.EmpID;
根据以下快照预期结果
答案 0 :(得分:2)
SELECT
e.FirstName,
c.CourseID,
c.CourseName
FROM tblEmployee e
LEFT JOIN tblEmpCourses ec ON e.ID =ec.EmpID
LEFT JOIN tblCourses c ON c.CourseID = ec.CourseID
类似的东西?
答案 1 :(得分:1)
select FirstName, CourseID, CourseName
from tblEmployee
left outer join tblEmpCourses
on tblEmployee.ID = tblEmpCourses.EmpID
left outer join tblCourses
on tblEmpCourses.CourseId = tblCourses.CourseId
答案 2 :(得分:0)
--Inner join for matching records
SELECT FirstName, C.CourseID ,tC.CourseName
FROM tblEmployee E
INNER JOIN
tblEmpCourses C
ON E.ID = C.EmpID
INNER join tblCourses tc
ON tc.CourseId=C.CourseID
输出
FirstName CourseID CourseName
FName1 1 Asp.net
FName1 2 C#
FName1 3 WebAPI
FName1 4 SQL