如果值存在于同一表的另一列中,如何查找对应的列值

时间:2019-01-19 13:55:24

标签: mysql sql

employee_name列具有所有具有相应employee_ID的雇员名称,manager_ID列具有其经理的所有雇员的employee_ID

在这里,我想让所有员工使用其mangers_names

注意:经理也是公司的雇员,因此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

1 个答案:

答案 0 :(得分:0)

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

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

Nb:当我们使用LEFT JOIN时,如果员工没有经理,它将出现在结果集中,而Manager_name为NULL。