简体   繁体   中英

What is a syntax to query a first_name of employees and first_name of their managers?

I know how to query first_name of all employees and first_name of all managers of departments separately but do not not know how to query a first_name of employees and first_name of their managers? The structure of both tables are following:

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

You would typically start from the employees table, then bring in the corresponding record in departments (the department he/she belongs to), and finally join again on employees to get the firstname of the departmnet manager:

select e.firstname employee_firstname, m.firstname manager_first_name
from employees e
inner join departments d on d.department_id = e.department_id
inner join employees m on m.employee_id = d.manager_id

Assuming that employee.manager_id points to the manager of an employee.

Then self-join the employees table on the manager_id.

SELECT 
 emp.first_name AS emp_first_name, 
 mgr.first_name AS mgr_first_name
FROM employees emp
LEFT JOIN employees mgr 
  ON mgr.employee_id = emp.manager_id
ORDER BY emp.first_name

And if you also want the manager of their departement.

SELECT 
 emp.first_name AS emp_first_name,
 mgr.first_name AS mgr_first_name,
 depmgr.first_name AS depmgr_first_name
FROM employees emp
LEFT JOIN employees mgr 
  ON mgr.employee_id = emp.manager_id
LEFT JOIN departments dep
  ON dep.department_id = emp.department_id
LEFT JOIN employees depmgr 
  ON depmgr.employee_id = dep.manager_id
ORDER BY emp.first_name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM