join with same table in mysql?

后端 未结 4 862
深忆病人
深忆病人 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: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
    

提交回复
热议问题