Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query to get the employee name and their manager name from the same table

Employee table

Employee_id  Employee_name   Manager_id
-------------------------------------
Emp00001     Ram             Emp00005
Emp00002     Sharath         Emp00003
Emp00003     Nivas           Emp00005
Emp00004     Praveen         Emp00002
Emp00005     Maharaj         Emp00002

Output

Employee Name    Manager Name
------------------------------
Ram              Maharaj
Sharath          Nivas
Nivas            Maharaj
Praveen          Sharath
Maharaj          Sharath

In the employee table, there are three columns Employee_id, employee_name and manager_id. From the table, how to fetch the employee name and their manager name?

like image 251
Sowbarani Karthikeyan Avatar asked Dec 17 '22 21:12

Sowbarani Karthikeyan


1 Answers

You can self-join the table to get the manager's name from his ID:

SELECT e.employee_name, m.employee_name AS manager_name
FROM   employee e
JOIN   employee m on e.manager_id = m.employee_id
like image 200
Mureinik Avatar answered Dec 20 '22 09:12

Mureinik