在这种情况下如何在MySQL中使用连接

时间:2017-05-16 04:45:30

标签: mysql sql join

我有一个员工表和一个部门表。如何使用join来获得下面所需的结果。员工表中的manager_id只是员工ID。请帮我找出答案

    Employee Table        

    id  | name  |   manager_id | department_id            
    ----------------------------------------              
    1   |  A    |   NULL       | 1                          
    2   |  B    |   1          | 2                        
    3   |  C    |   NULL       | 3                         
    4   |  D    |   3          | 2

     Department Table

     id    |   department_name
     -------------------------
     1    | Admin
     2    | HR
     3    | Finance 


    Required OutPut

    id  | name  |  manager_name   | department_name
    -----------------------------------------------
    1   |  A    |   NULL          | Admin                
    2   |  B    |   A             | HR                
    3   |  C    |   NULL          | Finance                
    4   |  D    |   C             | HR

3 个答案:

答案 0 :(得分:2)

同时使用内部联接和外部联接

select E1.ID, E1.Name, E2.Name, D.department_name
FROM Employee E1
LEFT OUTER JOIN Employee E2 ON E2.ID = E1.manager_id
INNER JOIN Department D ON D.id = E1.department_id

答案 1 :(得分:1)

SELECT E1.id, E1.name, E2.name as manager_name, D1.department_name
FROM Employee E1
LEFT JOIN Employee E2 ON (E1.id = E2.manager_id)
JOIN Department D2 ON (E1.department_id = D1.id)

您首先需要进行自我加入才能找到经理名称,之后需要加入部门以找到相应的部门名称。

答案 2 :(得分:0)

这会对你有帮助。

if idMutableArray.contains(hairStyleManIDArray[indexPath.row] as? String ?? "") {
    cell.accessoryType = .checkmark
}
else {
    cell.accessoryType = .none
}