【问题标题】:How to find corresponding column value if value exists in another column of same table如果同一表的另一列中存在值,如何找到对应的列值
【发布时间】:2019-01-19 13:55:24
【问题描述】:

employee_name 列包含所有员工姓名和对应的employee_ID,manager_ID 列包含所有员工的经理的employee_ID

在这里,我想获取所有员工的经理姓名

注意:经理也是公司的员工,所以 manager_ID ,employee_ID 包含相同的值

请看下表

select * from  test1.employee;

Employee_id Employee_Name  Manager_ID
1124        Annapurna      1125 
1125        Jaseel         
1126        Shilpa         1125

select employee_Name, employee_Name as manager_Name from
employee   where Employee_id  in (select Manager_ID from employee ) ;

RESULT:
employee_Name manager_Name
Jaseel         Jaseel         

select * from  test1.employee;

select employee_Name, employee_Name as manager_Name from
 employee   where Employee_id  in (select Manager_ID from employee ) ;


employee_Name manager_Name
Annapurna     jaseel
Shilpa        Annapurna

【问题讨论】:

  • 您在寻找一线经理吗?还是全部?
  • 在表中仅描述了员工的 manager_ID。我希望在这里获取所有人的经理姓名我可以根据employee_ID 从列employee_name 中获取经理姓名
  • 寻找recursive with

标签: mysql sql


【解决方案1】:

假设您只想向上搜索一级,如示例数据所示,您可以自行加入表,例如:

SELECT 
    t1.Employee_Name,
    t2.Employee_Name Manager_Name
FROM
    test1.employee t1
    LEFT JOIN test1.employee t2 
        ON t2.Employee_id = t1.Manager_id

注意:由于我们使用 LEFT JOIN,如果员工没有经理,它将出现在结果集中,Manager_name 为 NULL。

【讨论】:

    猜你喜欢
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多