我有这些表
用户
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
要求:
Page
,查询从该页面Read, Write, Delete
的{{1}}加Permission
中选择所有内容。@User_Id
,则应在@User_Id
中使用null
选择所有页面。Read, Write, Delete
中不存在@User_Id
,则Permission
应选为Read, Write, Delete
。null
包含某些permission
与pages
关联的记录,在这种情况下user
的所有记录都会出现对于那些没有关联pages
的网页,user_id
列中应该有null
。我做的是
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
但我想知道是否有其他方法可以解决这个。
答案 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