与mysql中的同一个表连接?

发布于 2024-11-09 09:39:10 字数 360 浏览 0 评论 0原文

我有下表,每个员工都有一个经理,如果一个人是他自己的经理,则 managerid 字段为空,我想要 emid 名称和经理 id 因为结果表名称是员工

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

,我想要结果为

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

心头的小情儿 2024-11-16 09:39:10
SELECT e1.emid, e1.name, COALESCE(e2.name, e1.name) AS managername
    FROM employee e1
        LEFT JOIN employee e2
            ON e1.managerid = e2.emid
SELECT e1.emid, e1.name, COALESCE(e2.name, e1.name) AS managername
    FROM employee e1
        LEFT JOIN employee e2
            ON e1.managerid = e2.emid
陌伤浅笑 2024-11-16 09:39:10

未经测试:

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

这只会产生真正有经理的员工。但这就是连接表本身的方式。

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.

快乐很简单 2024-11-16 09:39:10
select
      e1.emid,
      e1.name,
      COALESCE(e2.name, e1.name ) ManagerName
   from 
      employees e1
         left join employees e2
            on e1.managerid = e2.emid
select
      e1.emid,
      e1.name,
      COALESCE(e2.name, e1.name ) ManagerName
   from 
      employees e1
         left join employees e2
            on e1.managerid = e2.emid
抽个烟儿 2024-11-16 09:39: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

或者

SELECT emid, name, m.name managername
  FROM employees s
  LEFT JOIN employees m ON COALESCE(s.managerid, s.emid) = m.emid
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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文