我有3个表:Permissions,Role和RolePermissions。我想有一种方法可以基于RolePermissions表关系在Permissions表中选择缺少新行的Roles,以便在添加新权限后插入这些值。
我没有运气找到如何做到的,这就是为什么我在这里问。
表结构
Permissions | Roles | RolePermissions
------------------------------------------
Id | Id | Id
Name | Name | RoleId
| | PermissionId
sql的想法,但我知道这是不正确的:
-- Looking to be able to do something like
INSERT INTO RolePermissions (RoleId, PermissionId)
SELECT missingpermissions.PermissionId, missingpermissions.RoleId
FROM Permissions as p
INNER JOIN(
Select r.Id as RoleId, p.Id as PermissionId
FROM Role as r
LEFT JOIN RolePermissions as rp
ON r.Id = rp.RoleId
WHERE rp.PermissionId = p.Id
) as missingpermissions
ON p.id = missingpermissions.permissionid
已编辑为格式
答案 0 :(得分:1)
您需要获得新的权限并交叉加入所有角色(以获取角色和新权限的所有组合)。
INSERT INTO RolePermissions(RoleId, PermissionId)
SELECT r.ID AS RoleId,p.ID AS PermissionId
FROM Role r
CROSS JOIN (
--get all permissions currently not assigned to a role (presumably "new")
select p.*
from Permissions p
left join RolePermissions rp on p.id=rp.PermissionId
where rp.PermissionId is null
) p