从两个表中选择数据,其中子表的两列具有相同的外键

时间:2019-12-11 08:28:54

标签: sql-server

表1

StaffId int primary key,
StaffName nvarchar(150)

表2

DoctorIdRef int FOREIGN KEY REFERENCES Table1(StaffId),
AdminIdRef  int FOREIGN KEY REFERENCES Table1(StaffId),

这是我的两个表结构,我想选择类似的数据

select DoctorIdRef, DoctorName, AdminIdRef, AdminName

1 个答案:

答案 0 :(得分:1)

select DoctorIdRef, Doctor.StaffName DoctorName, AdminIdRef, Adminr.StaffName AdminName
from Table2 
left join Table1 as Doctor on Doctor.StaffId = Table2.DoctorIdRef 
left join Table1 as Adminr on Adminr.StaffId = Table2.AdminIdRef