0

以下に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'

現在、これら 2 人のユーザーの交差を取得しています。

User | Role    | User2 | Role2   
John | sysadmin| Jane  |Sysadmin 
4

1 に答える 1

1
WHERE U.Name ='John'
OR U2.Name='Jane'

AND ではなく OR に注意してください

なんで4列

    SELECT U.Name AS User,  
           R.rname AS Role   
    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
    where uName in ('','')
    order by 1, 2

これを試して

 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
   and U.Name ='John'

 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
   AND U2.Name='Jane'
于 2012-04-05T18:19:11.713 に答える