Programmer
Programmer

Reputation: 1294

How to join three SQL tables such that we can get information from the third?

Consider the three tables - Employee, Location and Department

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

How would one find the LocationName of a particular employee? E.g. how would we find the LocationName of EmployeeID 1234? We would have to get his/her DeptID, then match it with the Department.DepartmentID, and then match that Department.LocID to Location.LocationID and then get the LocationName of that LocID. Thanks

Upvotes: 0

Views: 21

Answers (1)

Sam Hartman
Sam Hartman

Reputation: 6489

Something like the following:

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

If you want to restrict the employees displayed you can add a where clause:

where employee.employeeID = 1234

Upvotes: 1

Related Questions