基于三个表创建视图,其中一个表中的列作为行

Create view based on three tables with columns as rows in one of tables

我开始学习 SQL,了解视图。 我想知道是否可以在一个视图中连接三个表,其中一些列将基于这些表中的行。

我有三个表:

角色:

Id | Name  | PermissionId
1  | Admin | 1
2  | Staff | 2

角色权限:

Id | RoleId | PermissionId
1  | 1      | 1
2  | 1      | 2
3  | 1      | 3
4  | 2      | 1
5  | 2      | 2      <- staff doesn't have permission 3

权限:

Id | Name
1  | Perm1
2  | Perm2
3  | Perm3
.
. (not fixed number of permissions)

我想创建这样的视图:

Id (of role) | Name  | Perm1 | Perm2 | Perm3  ... (not fixed number of columns)
1            | Admin | True  | True  | True
2            | Staff | True  | True  | False

可能吗?

如果您不知道要输出多少列,则不能使用视图。 下面的代码应该是你在正确的方向。如果您需要动态构建列列表

,请在带有动态 SQL 的过程中使用它
; With roles(Id, Name, PermissionID) as (
Select * From (values(1, 'Admin', '1'), (2, 'Staff', '2')) as r(Id, Name, PermissionId)
), RolePermissions(Id, RoleId, PermissionId) as (
Select * From (Values(1, 1, 1), (2, 1, 2), (3, 1, 3), (4, 2, 1), (5, 2, 2)) as p(Id, RoleId, PermissionId)
), Permissionss(Id, Name) as (
Select * From (Values(1, 'Perm1'), (2, 'Perm2'), (3, 'Perm3')) as p(Id, Name)
), data as(
Select r.Id, rp.PermissionId, p.Name From Roles as r
Inner Join RolePermissions as rp on rp.RoleId = r.Id
Inner Join Permissionss as p on rp.PermissionId = p.Id
)
Select piv.Id as [Id of Role], r.Name
, [Perm1] = case when [Perm1] is not null then 'true' else 'false' end
, [Perm2] = case when [Perm2] is not null then 'true' else 'false' end
, [Perm3] = case when [Perm3] is not null then 'true' else 'false' end
From data
Pivot( max(PermissionId)
For Name in ( [Perm1], [Perm2], [Perm3])
) as piv
Inner Join roles as r on r.Id = Piv.Id