消除此查询中的子查询

时间:2012-10-08 12:59:46

标签: sql join

我有这些表

用户

User_Id int PK, User_Name varchar(50)

网页

Page_Id int PK, Page_Name varchar(50)

权限

Permission_Id int PK , User_Id int FK, Page_Id int FK, 
Read bit, Write bit, Delete bit

要求:

  1. 根据提供的Page,查询从该页面Read, Write, Delete的{​​{1}}加Permission中选择所有内容。
  2. 如果未通过@User_Id,则应在@User_Id中使用null选择所有页面。
  3. 如果Read, Write, Delete中不存在@User_Id,则Permission应选为Read, Write, Delete
  4. 某些情况可能会有null包含某些permissionpages关联的记录,在这种情况下user的所有记录都会出现对于那些没有关联pages的网页,user_id列中应该有null
  5. 我做的是

    Read, Write, Delete

    这个查询工作正常并满足所有要求但是你可以看到它有declare @User_Id int=null; SELECT page.Page_Name, page.Page_Id, isnull((select Read from Permission where (@User_Id is null OR User_Id = @User_Id ) and (Permission.Page_Id = Page.Page_Id)),0) as Read, isnull((select Write from Permission where (@User_Id is null OR User_Id = @User_Id) and (Permission.Page_Id = Page.Page_Id)),0) as Write, isnull((select Delete from Permission where (@User_Id is null OR User_Id = @User_Id) and (Permission.Page_Id = Page.Page_Id)),0) as Delete, isnull((select Export from Permission where (@User_Id is null OR User_Id = @User_Id) and (Permission.Page_Id = Page.Page_Id)), 0) as Export FROM Page 我想要消除,一个选项可能是sub queries但我想知道是否有其他方法可以解决这个。

1 个答案:

答案 0 :(得分:2)

声明@User_Id int = null;

SELECT 
    page.Page_Name,
    page.Page_Id,
    ISNULL(Read,0) AS Read
    ISNULL(Write,0) AS Write,
    ISNULL(Delete,0) AS Delete,
    ISNULL(Export,0) AS Export
FROM 
    Page
    LEFT JOIN Permission ON Page.Page_ID = Permission.Page_ID AND Permission.User_ID = @User_ID

如果您也加入了@userID参数,那么当它为null时,它将与Permissions中的任何行都不匹配,因此您的值将为NULL