我有3张桌子
employees
-------------
|idEmployee |
| name |
user-employee
----------------
| idUser |-> MongoID
| idEmployee |-> FK employees.idEmployee
employees-supervisor
--------------------
| idEmployee |-> FK employees.idEmployee
| idUser |-> FK user-employee.idUser
我想要下一张桌子
idEmployee | name | idUser | nameSupervisor
1 | John | A2 | Jane
员工表包含公司的所有员工,用户员工拥有作为系统用户的所有员工,user-employee.idUser是mongo文档的用户,employees-supervisor具有匹配的列表idUser(mongoid),其id为employee(mysql)
我想要的是向所有员工展示他们各自的主管(如果有的话),现在我得到了idUser
SELECT employees.*, e1.idUser as idSupervisor, e2.name as supervisor
FROM employees
left JOIN user-employee e1 ON e1.idEmployee = employees.idEmployee
显示
idEmployee | name | idUser |
1 | John | 5887Ab |
我已经拥有主管的ID,现在我如何将该ID与用户 - 员工表上的名称相匹配?
答案 0 :(得分:0)
如果密钥不匹配我们可以使用左连接
SELECT employees.*, e1.idUser as idSupervisor, e3.name as supervisor
FROM employees
left JOIN `user-employee` e1 ON e1.idEmployee = employees.idEmployee
left JOIN `employees-supervisor` e2 on on e2.idUser = e.idUser
left JOIN employees e3 on e2.idEmployee = e3.idEmployee;
但如果表格中的关键字匹配,则应使用内连接
SELECT employees.*, e1.idUser as idSupervisor, e3.name as supervisor
FROM employees
INNER JOIN `user-employee` e1 ON e1.idEmployee = employees.idEmployee
INNER JOIN `employees-supervisor` e2 on on e2.idUser = e.idUser
INNER JOIN employees e3 on e2.idEmployee = e3.idEmployee;