我已经使用邻接模型来表示子/父关系。
它被用于镜像公司层次结构,每个员工都有一个经理。员工和经理都存储在同一个表中 - 因此managerID字段指的是特定经理的用户ID。
下面是我的表格结构: userID - email - password - firstName - lastName - officeID - departmentID - managerID - roleID - username
因此,managerID是外键,但源自相同的架构。
我要做的是显示一个表格,其中包含有关系统用户的信息 - 包括他们的经理是谁。
到目前为止,我已使用以下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
但是,我不确定如何显示经理的姓名。
任何帮助将不胜感激。
答案 0 :(得分:1)
只需使用managerID=m.userID
条件
m.firstName
和m.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 :(得分:1)
如果每个用户都有一个管理员(并且managerID不为空),您可以安全地将LEFT JOIN更改为内部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
答案 2 :(得分: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);