如何加入三个SQL表,以便我们可以从第三个获取信息?

时间:2017-09-21 17:37:01

标签: mysql sql

考虑三个表 - 员工,位置和部门

Employee:
EmployeeID
Name
DeptID

Department:
DepartmentID
DeptName
LocID

Location:
LocationID 
LocationName

Employee.DeptID is a foreign key to Department.DepartmentID. 
Department.LocID is a foreign key to Location.LocationID

如何找到特定员工的LocationName?例如。我们如何找到EmployeeID 1234的LocationName?我们必须获取他/她的DeptID,然后将其与Department.DepartmentID匹配,然后将该Department.LocID与Location.LocationID匹配,然后获取该LocID的LocationName。感谢

1 个答案:

答案 0 :(得分:1)

如下所示:

select employee.name, employee.employeeID, location.name from employee join department on department.departmentID = employee.departmentID join location on location.locationID = department.locID

如果要限制显示的员工,可以添加where子句:

where employee.employeeID = 1234