mySql N to N double join with null - CROSS join from answer

荒凉一梦 提交于 2020-01-07 01:53:29

问题


I have two tables one called permissions and one called roles which are related through a third table called RolePermissions in a N-N relationship.

Permissions
 id <- PK
 name


Roles
 id <- PK
 name

RolePermisions
 RoleId  <-PK
 PermissionId <-PK
 isAllowed

What I want is to get the full list of permissions of a specific role, and NULLs when there isn't a value in the RolePermission table for that Role. Left joins usually do the trick, but I can't work this one out.

Basically let's say I have the following values:

In Permsission:

1 - Per1
2 - Per2
3 - Per3

And in Roles:

1 - Role1
2 - Role2

And in RolePermissions:

RoleId  -  PermissionId - isAllowed
 1            1             true
 1            2             false
 1            3             true
 2            1             true

The following query sorta works but it will not return NULLs for those values not in RolePermissions:

select permissions.name, rolepermissions.allowed 
FROM permissions LEFT JOIN rolepermissions  
    ON rolepermissions.permissionId = permissions.id 
WHERE rolepermissions.roleId = 2;

The result I would be looking for when querying for Role 2 is

Per1 - true
Per2 - NULL
Per3 - NULL

回答1:


You can do this with a CROSS JOIN:

SELECT
    r.ID AS RoleID,
    p.ID AS PermissionID,
    rp.IsAllowed
FROM
    Roles r CROSS JOIN
    Permissions p LEFT JOIN
    RolePermissions rp ON rp.RoleId = r.ID AND rp.PermissionID = p.ID
WHERE r.ID = @RoleID


来源:https://stackoverflow.com/questions/9675947/mysql-n-to-n-double-join-with-null-cross-join-from-answer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!