0

我有一个RoleDetails以此结构命名的表:

ROLE_ID - PK , 
NAME ,
PARENT_ROLE_ID FK ,
CREATED_BY_ID , 
MODIFIED_BY_ID

另一张桌子是user_details

USER_ID ,
USERNAME ,
FULLNAME

如何查询此表,以便在结果集中获得 RoleName、RoleId、ParentRoleId、ParentRoleName、CreatedByName 和 ModifiedByName。

到目前为止,我已经尝试过:

SELECT 
    [ROLE_ID] AS ID, r.NAME AS [RoleName], 
    r.PARENT_ROLE_ID AS [ParentRoleID] , 
    (SELECT rd.NAME FROM dbo.ROLES rd 
     WHERE rd.ROLE_ID = r.PARENT_ROLE_ID ) AS [ParentRoleName], 
    CONCAT(ud.FIRST_NAME, ' ', ud.LAST_name) AS [CreatedByName] , 
    CONCAT(u.FIRST_NAME, ' ', u.LAST_name) AS [LastModifiedByName] 
FROM 
    dbo.ROLES r 
LEFT OUTER JOIN 
    user_details u ON r.MODIFIED_BY = u.USER_ID 
LEFT OUTER JOIN 
    dbo.USER_DETAILS ud ON r.CREATED_BY = ud.USER_ID 
WHERE 
    r.ROLE_ID = @iRoleID;
4

1 回答 1

1

您将需要加入该user_detail表两次。一次获取创建用户,一次获取修改用户。

SELECT    rd.Name, 
          rd.Role_ID, 
          rd.Parent_role_id,
          pr.Name, 
          ud.userName as CreatedByName, 
          udm.userName as ModifyByName
FROM RoleDetails as rd
INNER JOIN RoleDetails as pr
ON rd.Parent_Role_Id = pr.Role_id
INNER JOIN User_Detail as ud
on rd.Created_by_id = ud.user_id
INNER JOIN User_Detail as udm
ON rd.Modified_by_user = udm.user_id
于 2013-05-31T15:10:55.353 回答