2016-10-06 71 views
0

我有4個表內連接多個表得到名稱,而不是ID

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 

但在創建並authorizated我得到一個ID,abc123,我想要的是將id與一個名稱相匹配,該id在表格用戶 - 員工

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

我想要John Doe出現而不是id。

回答

0

發生率 - 員工。*正在爲您提供該表中的所有字段,其中包括兩個ID。一種方法是再做兩次連接,將員工表加入employee.idemployee = incidents-employee.createdby和authorizedby的事件表中。

然後,而不是使用。*,你引用你想要的每個字段。你也會讓事情變得更容易通過使用別名,如:

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

那麼你可以參考E1.name爲createdby名。

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,那麼我建議使用左加入,而不是內部聯接

+0

二隊,如果你打算基本反映以前的答案,至少應該承認它會很好。我採取了引導他解決問題的方法,而不是將整個查詢交給他。我們的兩種方法都不是更正確或錯誤......仍然...請注意這一點。謝謝。 – nycdan

+0

我認爲我們方法的主要區別在於,您沒有使用或建議在答案中使用的聯結表(用戶 - 員工)。 – Jayvee

+0

在這部分'e1.name as createdBy,e2.name'中,mysql如何知道你引用了哪個表?,而不是'incidents-master.name',我們明確地說表名 –