我有三张桌子
权限
id | name
1 | do.this
2 | do.that
3 | dont.this
4 | dont.that
5 | neither.this
6 | both.that
角色
id | name
1 | doer
2 | donter
权限角色
permission_id | role_id
1 | 1
2 | 1
6 | 1
3 | 2
4 | 2
6 | 2
所以通过下面的查询,我们可以得到一个用户拥有的所有角色
permission_id | permission_name | role_id | role_name
1 | do.this | 1 | doer
2 | do.that | 1 | doer
6 | both.that | 1 | doer
3 | dont.this | 2 | donter
4 | dont.that | 2 | donter
6 | both.that | 2 | donter
查询
SELECT
p.id AS permission_id, p.name AS permission_name,
r.id AS role_id, r.name AS role_name FROM permission_role pr
JOIN permissions p ON pr.`permission_id` = p.id
JOIN roles r ON pr.`role_id` = r.id;
问题
我想知道的是,我们如何反转此查询,以便创建一个结果集,列出角色不具有的所有权限,以便:
permission_id | permission_name | role_id | role_name
3 | dont.this | 1 | doer
4 | dont.that | 1 | doer
5 | neither.this | 1 | doer
1 | do.this | 2 | donter
2 | do.that | 2 | donter
5 | neither.this | 2 | donter
最佳答案
这种类型的查询逻辑从生成角色和权限的所有组合开始,然后删除存在的组合(使用left outer join
)。
select p.id as permission_id, p.name as permission_name,
r.id as role_id, r.name as role_name
from roles r cross join
permissions p left outer join
permission_role pr
on pr.permission_id = p.id and
pr.role_id = r.id
where pr.role_id is null;
关于mysql - 在mysql中显示非连接行的映射?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22128842/