How to get the employees with their managers

后端 未结 5 1462
生来不讨喜
生来不讨喜 2020-12-29 12:16

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           


        
5条回答
  •  清酒与你
    2020-12-29 13:08

    (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)
    

提交回复
热议问题