视图中的一对多SELECT语句

时间:2010-08-19 17:52:36

标签: tsql

数据库中有3个表:

Users (UserID, UserName), Roles(RoleID, RoleName) and UserRoles(UserID, RoleID)

如何在具有IsAdmin列的Users表上创建视图,这里是一个模型:

CREATE VIEW UsersView AS
    SELECT
        u.UserID,
        u.UserName,
        CASE WHEN ur.RoleID IS NULL THEN (0) ELSE (1) END AS IsAdmin
    FROM Users AS u
        LEFT JOIN Roles AS r ON r.RoleName = N'Admins'
        LEFT JOIN UserRoles AS ur ON  ur.UserID = u.UserID
                                  AND ur.RoleID = r.RoleID

IsAdmin应该是(1)如果用户是“Admins”用户角色,而(0)如果他不是

5 个答案:

答案 0 :(得分:1)

试试这个

这是另一种方式......但我确实喜欢Charles Bretana发布的EXISTS版本

CREATE VIEW UsersView AS
SELECT UserID,UserName, MAX(IsAdmin) as IsAdmin
FROM(SELECT
    u.UserID,
    u.UserName,
    CASE r.RoleName when 'Admins' then 1 else 0 end AS IsAdmin
FROM Users AS u
    LEFT JOIN UserRoles AS ur ON ur.UserID = u.UserID
    LEFT JOIN Roles r on ur.RoleID = r.RoleID) x
    GROUP BY UserID,UserName

答案 1 :(得分:1)

尝试:

  CREATE VIEW UsersView AS 
    SELECT 
        u.UserID, 
        u.UserName, 
        Case When Exists
           (Select * from userRoles ur
                Join Roles r On r.RoleId = ur.Roleid
            Where ur.userId = u.UserId
               And r.RoleName = '"Admins') 
          Then 1 Else 0 End IsAdmin 
    FROM Users u 

答案 2 :(得分:1)

这种方法很有效。注意添加新的角色检查是多么微不足道。

<强>代码

Declare @Users Table(UserID Int, UserName VarChar(256))
Declare @Roles Table(RoleID Int, RoleName VarChar(256))
Declare @UserRoles Table(UserID Int, RoleID Int)

Insert Into @Roles Select 1, 'Admins'
Insert Into @Roles Select 2, 'Role2'
Insert Into @Roles Select 3, 'Role3'
Insert Into @Roles Select 4, 'Genius'

Insert Into @Users Select 1, 'Phil'
Insert Into @UserRoles Select 1, 1
Insert Into @UserRoles Select 1, 2
Insert Into @UserRoles Select 1, 3
Insert Into @UserRoles Select 1, 4

Insert Into @Users Select 2, 'Jim'
Insert Into @UserRoles Select 2, 2
Insert Into @UserRoles Select 2, 3

Insert Into @Users Select 3, 'Susan'
Insert Into @UserRoles Select 3, 1
Insert Into @UserRoles Select 3, 2
Insert Into @UserRoles Select 3, 3


Select UserID,
       UserName,
       Cast([Admins] As Bit) As IsAdmin,
       Cast([Genius] As Bit) As IsGenius
From (
    Select  Users.UserID,
            Users.UserName,
            Roles.RoleName
    From @Users As Users
        Left Join @UserRoles As UserRoles On UserRoles.UserID = Users.UserID
        Left Join @Roles As Roles On UserRoles.RoleID = Roles.RoleID
) As Data
Pivot (
    Count(RoleName) For RoleName In (
        [Admins], [Genius]
    )
) As Result

<强>结果

UserID  UserName IsAdmin IsGenius
2       Jim      0       0
1       Phil     1       1
3       Susan    1       0

答案 3 :(得分:0)

在Roles表中添加另一列isAdmin,并仅为Admin角色将其设置为true。然后,在视图等中,检查where子句中的isAdmin标记。

答案 4 :(得分:0)

我自己的解决方案看起来更好。