join with same table in mysql?

后端 未结 4 858
深忆病人
深忆病人 2021-01-21 04:58

Im having the following table , each employee have a manager, if a guy is his own manager den the managerid field is null, i want emid name and manager id as result

相关标签:
4条回答
  • 2021-01-21 05:01
    select
          e1.emid,
          e1.name,
          COALESCE(e2.name, e1.name ) ManagerName
       from 
          employees e1
             left join employees e2
                on e1.managerid = e2.emid
    
    0 讨论(0)
  • 2021-01-21 05:10
    SELECT emid, name,
           CASE WHEN s.managerid IS NULL THEN s.name ELSE m.name END managername
      FROM employees s
      LEFT JOIN employees m ON s.managerid = m.managerid
    

    OR

    SELECT emid, name, m.name managername
      FROM employees s
      LEFT JOIN employees m ON COALESCE(s.managerid, s.emid) = m.emid
    
    0 讨论(0)
  • 2021-01-21 05:13

    UNTESTED:

    select a.name as name, b.name as managername from employee a inner join employee b on a.managerid=b.emid
    

    This will only yield the employees who actually have a manager. But this is how you join a table on itself.

    0 讨论(0)
  • 2021-01-21 05:17
    SELECT e1.emid, e1.name, COALESCE(e2.name, e1.name) AS managername
        FROM employee e1
            LEFT JOIN employee e2
                ON e1.managerid = e2.emid
    
    0 讨论(0)
提交回复
热议问题