SQL Server 2012查询 - 来自同一表的外键

时间:2013-05-31 15:06:51

标签: sql sql-server-2012

我有一个名为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;

1 个答案:

答案 0 :(得分: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