考虑表格:
和WorkersBosses(多对多)
我如何让所有员工与他们的老板(如果一个工人有一个老板,所以把它放在他身边,否则只是放一个空)。
有了这个:
SELECT TOP 1000 [EmployeeName] ,workboss.bossid
FROM [TestingDB].[dbo].[Worker] as workers
LEFT OUTER JOIN [TestingDB].[dbo].[WorkersBosses] as workboss
on workers.EmployeeId = workboss.WorkerId
我让所有员工都带着他们的老板,但我怎么能得到老板的名字(而不仅仅是他的身份证)?
由于
答案 0 :(得分:1)
将INNER JOIN
添加到Worker
:
SELECT
w.EmployeeName AS EmployeeName,
wb.BossName
FROM Worker w
LEFT JOIN(
SELECT b.WorkerId, b.BossId, w2.EmployeeName AS BossName
FROM WorkersBoss b
INNER JOIN Worker w2
ON w2.EmployeeId = b.BossId
)wb
ON w.EmployeeId = wb.WorkerId
这也可以写成:
SELECT
w.EmployeeName AS EmployeeName,
w2.EmployeeName AS BossName
FROM Worker w
LEFT JOIN WorkersBosses wb
INNER JOIN Worker w2
ON w2.EmployeeId = wb.BossId
ON w.EmployeeId = wb.WorkerId
答案 1 :(得分:1)
只需使用不同的别名即可多次加入同一个表:
SELECT w.EmployeeId,
w.EmployeeName,
b.EmployeeId AS BossEmployeeId,
b.EmployeeName AS BossEmployeeName
FROM Worker w
LEFT JOIN WorkersBosses wb
ON wb.WorkerId = w.EmployeeId
LEFT JOIN Worker b
ON b.EmployeeId = wb.BossId