内连接多个表获取名称而不是id

时间:2016-10-06 17:08:22

标签: mysql

我有4张桌子

Table incidences-employees
---------------------------
idIncidenceEmployee PK
idEmployee FK (employee.idemployee)
idMasterIncidence FK (incidence-master.idIncidence)
createdby FK (user-employee.idMongoUser)
authorizedBy FK (user-employee.idMongoUser)

Table incidence-master
---------------------------
idIncidence PK
name

TAble user-employee
--------------------------
idMongoUser PK
idEmployee

Table EMployee
-------------------------
idEmployee Pk
name
lastName

我做这个查询

SELECT employee.name, incidences-master.name, incidences-employees.* 
  FROM employee-incidences 
    INNER JOIN employee ON employee.idEmployee = employee-incidences.idEmployee 
    INNER JOIN incidences-master ON incidences-master.idIncidence = employee-incidences.idIncidenceEmployee

我明白了

Employee name | Incidence name | idIncidenceEmployee | idEmployee | idMasterIncidence | createdby | authorizedBy 
John Doe      | Incidence Name |               1     |    1       |                 5 |    abc123 | abc123

但是在我创建和授权的时候,我得到了一个ID,abc123,我想要的是将id与一个名称相匹配,那个id就是表user-employee

    Table user-employee          Table Employee
   ----------------------    -   -------------------
    idMongoUser -> abc123        idEmployee -> 1
    idemployee -> 1              Name -> John Doe

我希望John Doe出现而不是id。

2 个答案:

答案 0 :(得分:0)

occurrence事件 - 员工。*正在为您提供该表中的所有字段,其中包括两个ID。一种方法是再进行两次连接,将employee表连接到employees.idemployee = incidents-employee.createdby和authorizedby的eventss表。

然后,您可以引用所需的每个字段,而不是使用。*。您还可以使用以下别名来简化操作:

select ... from incidences-employee I
join employee E1 on E1.idemployee = I.createdby

然后,您可以为已创建的名称引用E1.name。

答案 1 :(得分:0)

你可能想要这样的东西:

SELECT employee.name as employeeName, incidences-master.name as incidenceName, e1.name as createdBy, e2.name as authorisedBy
FROM employee-incidences 
INNER JOIN incidences-master ON incidences-master.idIncidence = employee-incidences.idIncidenceEmployee
INNER JOIN employee ON employee.idEmployee = employee-incidences.idEmployee
INNER JOIN user-employee ue1 on ue1.idMongoUser = employee-incidences.createdBy
INNER JOIN employee e1 on e1.idEmployee = ue1.idEmployee
INNER JOIN user-employee ue2 on ue2.idMongoUser = employee-incidences.AuthorizedBy
INNER JOIN employee e2 on e2.idEmployee = ue2.idEmployee

如果有某些情况,createdBy或authorisedBy可能为空或null,那么我建议使用Left Joins而不是Inner Joins