2011-03-08 35 views
0

我已經利用鄰接模型來表示一個子/父關係。鄰接模型MySQL語法

它被用來反映公司層次結構,每個員工都有一個經理。員工和經理都存儲在同一個表中 - 所以managerID字段指的是特定經理的用戶標識。

下面是我的表結構: 用戶ID - 電子郵件 - 密碼 - 的firstName - lastName的 - officeID - DepartmentID的 - 經理ID - 角色ID - 用戶名

所以經理I​​D是一個外鍵,但在相同的模式起源。

我試圖做的是顯示一張包含系統用戶信息的表格 - 包括他們的經理是誰。

到目前爲止,我已經實現了與下面的SQL語句這種使用多個連接:

SELECT user.firstName, user.lastName, office.officeName, department.departmentTitle, role.roleName 
FROM user, office, department, role 
WHERE user.officeID = office.officeID 
AND user.departmentID = department.departmentID 
AND user.roleID = role.roleID 

但是,我如何顯示經理的姓名上不確定。

任何幫助,將不勝感激。

回答

1

您的查詢僅提取用戶。要獲得經理姓名,您需要重新加入用戶表,如下所示:

SELECT u.firstName, u.lastName, 
     o.officeName, d.departmentTitle, 
     r.roleName, 
     m.firstName AS mFN, m.lastName AS mLN 
FROM user u JOIN office o ON (u.officeID = o.officeID) 
      JOIN department d ON (u.departmentID = d.departmentID) 
      JOIN role r ON (u.roleID = r.roleID) 
      JOIN user m ON (u.manager_id=m.user_id); 
1

只是managerID=m.userID條件再次攜手用戶表

m.firstNamem.lastName是經理的名字

SELECT user.firstName, user.lastName, m.firstName,m.lastName, office.officeName, department.departmentTitle, role.roleName 
FROM user as u, user as m, office, department, role 
WHERE u.officeID = office.officeID 
AND u.departmentID = department.departmentID 
AND u.roleID = role.roleID 
AND u.managerID=m.userID 
1

如果每個用戶都有一個管理器(和經理ID不爲空),你可以安全地更改左加入內部JOIN。

SELECT u.firstName 
    , u.lastName 
    , office.officeName 
    , department.departmentTitle 
    , role.roleName 
    , manager.firstName AS managerFirstName 
    , manager.lastName AS managerLastName 
    FROM user AS u 
    JOIN office 
     ON u.officeID = office.officeID 
    JOIN department 
     ON u.departmentID = department.departmentID 
    JOIN role 
     ON u.roleID = role.roleID 
    LEFT JOIN user AS manager 
     ON u.managerID = manager.userID