Sql 联接表的子查询

Sql 联接表的子查询,sql,subquery,Sql,Subquery,我正在写一个问题,需要一些帮助。我把它分解成最简单的形式。 我的表格结构示例如下所示(为了清晰起见,我对其进行了修改): 我需要做的是,允许创建文档的用户能够查看他们自己的文档。 因此,我使用: CREATE PROCEDURE GetUsersDocuments @UserId INT = null AS BEGIN SET NOCOUNT ON; Select * from Documents D Where D.CreatedBy = I

我正在写一个问题,需要一些帮助。我把它分解成最简单的形式。 我的表格结构示例如下所示(为了清晰起见,我对其进行了修改):

我需要做的是,允许创建文档的用户能够查看他们自己的文档。 因此,我使用:

CREATE PROCEDURE GetUsersDocuments
    @UserId         INT = null
AS
BEGIN

    SET NOCOUNT ON;

    Select * from Documents D
    Where D.CreatedBy = ISNULL(@UserId, D.CreatedBy)
END
它返回由特定用户创建的所有文档

但是,模型的业务规则还规定,其他用户可以代表用户创建文档。因此,用户需要查看自己创建的所有记录,以及他们拥有所有权的所有文档:

CREATE PROCEDURE GetUsersDocuments
    @UserId         INT = null
AS
BEGIN

    SET NOCOUNT ON;

    Select * from Documents D
    Where D.CreatedBy = ISNULL(@UserId, D.CreatedBy)
    OR D.DocumentOwner = ISNULL(@UserId, D.DocumentOwner)
END
一切都很好。但是,我刚刚得知,用户的所有直接下属都应该能够看到用户创建的文档和用户拥有的文档

给定我定义的示例表结构,我将如何用查询来表示它

非常感谢

Select * from Documents D 
Where D.CreatedBy = ISNULL(@UserId, D.CreatedBy) 
    OR D.DocumentOwner = ISNULL(@UserId, D.DocumentOwner)  
    OR D.DocumentOwner = ( select ManagerID from DirectReports where @UserId = UserID)
Select * from Documents D 
Where D.CreatedBy = ISNULL(@UserId, D.CreatedBy) 
    OR D.DocumentOwner = ISNULL(@UserId, D.DocumentOwner)  
    OR D.DocumentOwner = ( select ManagerID from DirectReports where @UserId = UserID)