This is what I want the output to look like:
Employee Emp# Manager Mgr#
BLAKE 7698 KING 7839
CLARK 7782 KING 7839
JONES 7566 KING
This is a classic self-join, try the following:
SELECT e.ename, e.empno, m.ename as manager, e.mgr
FROM
emp e, emp m
WHERE e.mgr = m.empno
And if you want to include the president which has no manager then instead of an inner join use an outer join in Oracle syntax:
SELECT e.ename, e.empno, m.ename as manager, e.mgr
FROM
emp e, emp m
WHERE e.mgr = m.empno(+)
Or in ANSI SQL syntax:
SELECT e.ename, e.empno, m.ename as manager, e.mgr
FROM
emp e
LEFT OUTER JOIN emp m
ON e.mgr = m.empno
(SELECT ename FROM EMP WHERE empno = mgr)
There are no records in EMP that meet this criteria.
You need to self-join to get this relation.
SELECT e.ename AS Employee, e.empno, m.ename AS Manager, m.empno
FROM EMP AS e LEFT OUTER JOIN EMP AS m
ON e.mgr =m.empno;
EDIT:
The answer you selected will not list your president because it's an inner join. I'm thinking you'll be back when you discover your output isn't what your (I suspect) homework assignment required. Here's the actual test case:
> select * from emp;
empno | ename | job | deptno | mgr
-------+-------+-----------+--------+------
7839 | king | president | 10 |
7698 | blake | manager | 30 | 7839
(2 rows)
> SELECT e.ename employee, e.empno, m.ename manager, m.empno
FROM emp AS e LEFT OUTER JOIN emp AS m
ON e.mgr =m.empno;
employee | empno | manager | empno
----------+-------+---------+-------
king | 7839 | |
blake | 7698 | king | 7839
(2 rows)
The difference is that an outer join returns all the rows. An inner join will produce the following:
> SELECT e.ename, e.empno, m.ename as manager, e.mgr
FROM emp e, emp m
WHERE e.mgr = m.empno;
ename | empno | manager | mgr
-------+-------+---------+------
blake | 7698 | king | 7839
(1 row)
Perhaps your subquery (SELECT ename FROM EMP WHERE empno = mgr)
thinks, give me the employee records that are their own managers! (i.e., where the empno of a row is the same as the mgr of the same row.)
have you considered perhaps rewriting this to use an inner (self) join? (I'm asking, becuase i'm not even sure if the following will work or not.)
SELECT t1.ename, t1.empno, t2.ename as MANAGER, t1.mgr
from emp as t1
inner join emp t2 ON t1.mgr = t2.empno
order by t1.empno;
TRY THIS
SELECT E.ename,E.empno,ISNULL(E.ename,'NO MANAGER') AS MANAGER FROM emp e
INNER JOIN emp M
ON M.empno=E.empno
Instaed of subquery use self join
You could have just changed your query to:
SELECT ename, empno, (SELECT ename FROM EMP WHERE empno = e.mgr)AS MANAGER, mgr
from emp e
order by empno;
This would tell the engine that for the inner emp table, empno should be matched with mgr column from the outer table.