我有两张表Users
和Details
。 UserId
是Users
的主键。
另一方面,来自UserId
的{{1}}列是来自表Details
的参考。
表:用户
Users
表:详细信息
UserId FirstName Lastname
1 John Wick
2 Black Panther
3 Lebron James
如果我要执行如下查询:
UserId ManagerId SupervisorId
1 3 2
2 3 1
3 3 1
结果将是:
表:详细信息
SELECT * FROM Users INNER JOIN Details on Users.UserId = Details.UserId
我想要实现的目标是:
UserId FirstName LastName ManagerId SupervisorId
1 John Wick 3 2
2 Black Panther 3 1
3 Lebron James 3 1
基本上使用其引用键表中的另一列。我该怎么做?
答案 0 :(得分:3)
主管和经理的ID在用户表中?您将多次使用别名加入同一个表:
SELECT Details.*, U1.FirstName AS UserFirstName, U1.LastName AS UserLastName,
U2.FirstName AS ManagerFirstName, U2.LastName AS ManagerLastName,
U3.FirstName AS SupervisorFirstName, U3.LastName AS SupervisorLastName
FROM Details
INNER JOIN Users U1 ON U1.UserId = Details.UserId
INNER JOIN Users U2 ON U2.UserID= Details.ManagerID
INNER JOIN Users U3 ON U3.UserID= Details.SupervisorID
答案 1 :(得分:3)
您可以多次加入表格。因此,您可以将Users表连接到Details表,然后再次返回Users表。你只需要给表格别名。
select
u.UserId, u.FirstName, u.LastName,
m.FirstName as ManageId,
d.FirstName as SupervisorId
from
Users u
inner join Details d
on (u.UserId=d.UserId)
inner join Users m -- Manager
on (m.UserId=d.ManagerId)
inner join Users s -- Supervisor
on (s.UserId=d.ManagerId)