在mysql中加入相同的表?

时间:2021-06-07 01:09:25

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 table name is employee

我有下面的表,每个员工都有一个经理,如果一个人是他自己的经理,那么managerid字段为null,我想要emid名和managerid,因为结果表名是employee

emid name managerid
1    raj  null
2    ram   1
3    ravi   null
4    arvind  3
5    rithu   2

and i want the result as

我想要的结果是

emid name managername
1    raj  raj
2    ram   raj
3    ravi   ravi
4    arvind  ravi
5    rithu   ram

4 个解决方案

#1


2  

SELECT e1.emid, e1.name, COALESCE(e2.name, e1.name) AS managername
    FROM employee e1
        LEFT JOIN employee e2
            ON e1.managerid = e2.emid

#2


1  

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.

这只会产生真正有经理的员工。但这就是如何加入一个表的方法。

#3


0  

select
      e1.emid,
      e1.name,
      COALESCE(e2.name, e1.name ) ManagerName
   from 
      employees e1
         left join employees e2
            on e1.managerid = e2.emid

#4


0  

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

#1


2  

SELECT e1.emid, e1.name, COALESCE(e2.name, e1.name) AS managername
    FROM employee e1
        LEFT JOIN employee e2
            ON e1.managerid = e2.emid

#2


1  

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.

这只会产生真正有经理的员工。但这就是如何加入一个表的方法。

#3


0  

select
      e1.emid,
      e1.name,
      COALESCE(e2.name, e1.name ) ManagerName
   from 
      employees e1
         left join employees e2
            on e1.managerid = e2.emid

#4


0  

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