帮助sql查询

时间:2010-10-12 16:05:35

标签: sql sql-server tsql

我正在进行sql查询,我想返回一个列表,其中包含可以访问应用程序的用户/组。这是方案,我们将看到用户是否拥有权限,如果没有,我们将看到该组。如果两者都没有,我们会看到该应用程序是否有任何权限,如果没有,则会将用户添加到权限中,如果用户或组具有我们添加的权限。

SELECT 
    dbo.APPLICATIONS_PERMISSION.USERMASTERID,
    dbo.APPLICATIONS_PERMISSION.GROUPID,
    dbo.APPLICATIONS_PERMISSION.VISIBLE, 
    dbo.APPLICATIONS_PERMISSION.APPLICATIONID
FROM dbo.GROUP 
RIGHT OUTER JOIN
dbo.APPLICATIONS_PERMISSION ON
dbo.GROUP.ID = dbo.APPLICATIONS_PERMISSION.GROUPID 
FULL OUTER JOIN
dbo.USER_MASTER ON 
dbo.APPLICATIONS_PERMISSION.USERMASTERID = dbo.USER_MASTER.ID 
AND dbo.GROUP.ID = dbo.USER_MASTER.GROUPID
WHERE (dbo.APPLICATIONS_PERMISSION.USERMASTERID = 7) 
AND (dbo.APPLICATIONS_PERMISSION.APPLICATIONID = 3)

CNC中 表格式

User_Master
  ID
  Name
  GroupID

Aplications_Permissions
   ID
   AplicationsID
   UsermasterID
   GroupID

GROUP
   ID
   Name


--Data Exemple --
User_Master
1 ; Filipe ; 1
2 ; Luis ; 1
3 ; Daniel ; 2
4 ; Toino ; 3

Aplications_Permissions
1 ; 1 ; 2 ; null
2 ; 1 ; null ; 1

Group
1 abc
2 def
3 poi


Result:
input: dbo.APPLICATIONS_PERMISSION.USERMASTERID = 2 // dbo.APPLICATIONS_PERMISSION.APPLICATIONID = 1

will return
True
-----------------------------------------
input: dbo.APPLICATIONS_PERMISSION.USERMASTERID = 3 // dbo.APPLICATIONS_PERMISSION.APPLICATIONID = 1

will return
True
-----------------------------------------
input: dbo.APPLICATIONS_PERMISSION.USERMASTERID = 3 // dbo.APPLICATIONS_PERMISSION.APPLICATIONID = 2

will return
True (because nobody have permissions in that application)
-----------------------------------------
input: dbo.APPLICATIONS_PERMISSION.USERMASTERID = 3 // dbo.APPLICATIONS_PERMISSION.APPLICATIONID = 2

will return
False(dont have permissions, and dont belong to that group)

1 个答案:

答案 0 :(得分:0)

为了便于阅读,可以自由地对表进行别名处理:

SELECT ap.USERMASTERID, ap.GROUPID, ap.VISIBLE, ap.APPLICATIONID
FROM dbo.GROUP g
RIGHT OUTER JOIN dbo.APPLICATIONS_PERMISSION ap ON g.ID = ap.GROUPID 
FULL OUTER JOIN dbo.USER_MASTER um 
     ON ap.USERMASTERID = um.ID AND g.ID = um.GROUPID
WHERE (um.ID = 7) AND (ap.APPLICATIONID = 3)

如果我理解正确,听起来我们想要返回一个用户列表,这些用户对该应用程序拥有直接权限,或者是拥有该应用程序权限的群组成员。

让我们分别通过这两个查询来简化它:

--Direct permission
SELECT ap.USERMASTERID, NULL AS 'GROUPID', ap.VISIBLE, ap.APPLICATIONID
FROM dbo.APPLICATIONS_PERMISSION ap
INNER JOIN dbo.USER_MASTER um ON ap.USERMASTERID = um.ID
WHERE (ap.USERMASTERID = 7) AND (ap.APPLICATIONID = 3)

UNION ALL

--Permission through group membership
SELECT ap.USERMASTERID, ap.GROUPID, ap.VISIBLE, ap.APPLICATIONID
FROM dbo.APPLICATIONS_PERMISSION ap
INNER JOIN dbo.Group g ON ON g.ID = ap.GROUPID 
INNER JOIN dbo.USER_MASTER um ON g.USERMASTERID = um.ID
WHERE (um.ID = 7) AND (ap.APPLICATIONID = 3)

可能必须稍微玩一下才能得到你需要的东西,但我会说:分开做。可能甚至不需要连接到User_Master表,因为它看起来好像你实际上从它检索任何字段。只需从ap.UserMasterID或g.UserMasterID过滤。