Reputation: 3
I am new to SQL i have just started to learn SQL. I have an Employee table which has 3 columns :
when manager_id is same as id means an employee will have another employee as manager.
For example:
Employee "AAA" will have "BBB" as his manager if employee record has id of employee "BBB" as manager_id.
How could I write an single SQL query which would give me result of "Employee name" and their corresponding "Manager_name".
Below are the details of Table, Queries tried so far and The expected result.
Employee Table:
select * from test.employee;
Query 1:
SELECT name as manager_name FROM test.employee
where manager_id IN(select id from test.employee)
group by manager_id;
Query 2:
SELECT name as emp_name FROM test.employee
How could I achieve the combined result of Query 1 and Query 2 i.e as shown below:
Upvotes: 0
Views: 27
Reputation: 12318
You need to have the same table twice and give it an alias, something like this:
SELECT e.name, m.name as manager_name
FROM test.employee e
join test.employee m on e.manager_id = m.id
If there's employees where manager doesn't exist, you might want to use left outer join
instead
Upvotes: 2