我在下面有 3 张桌子。我正在尝试比较每个用户的角色。那就是我想显示 John 有 2 个角色,而 Jane 有 1 个角色。目前我只显示它们之间的共同角色。
Sec_role (PK R_KEY, rname)
Role_User(PK R_KEY, PK USER_KEY)
User(PK USER_KEY, Name)
样本数据:
Sec_Role Role_User User
R_Key|rname| R_Key|User_Key User_KEY|NAME
1 |Analyst 1 |1 1 |John
2 |Sysadmin 2 |1 2 |Jane
2 |2
我想得到
User | Role | User2 | Role2
John | Analyst | Jane | (Empty because she isn't an analyst)
John | sysadmin| Jane |Sysadmin
SELECT U.Name AS User1,
U2.Name AS User2,
R.rname AS Role1
R2.Rname AS Role2
FROM Sec_Role AS R
LEFT OUTER JOIN Role_User AS RU
ON R.R_Key=RU.R_Key
LEFT OUTER JOIN User AS U
ON U.User_Key=RU.User_Key
LEFT OUTER JOIN Sec_Role AS R2
ON R2.R_Key=R.R_Key <---(I think this is the issue here)
LEFT OUTER JOIN Role_User AS RU2
ON R2.R_Key=RU2.R_Key
LEFT OUTER JOIN User AS U2
ON U2.User_Key=RU2.User_Key
WHERE U.Name ='John'
AND U2.Name='Jane'
目前我正在获得这两个用户的交集。
User | Role | User2 | Role2
John | sysadmin| Jane |Sysadmin