说明:单个简单查询是非常容易的,但是为了避免多次访问访问数据库,我们会尽可能通过表关联将业务所需要的字段值一次性查出来。而有时候不太清楚表之间的关联关系(这取决于对业务的熟悉程度),或者实际情况就是少了一张关联表,导致我们不能通过关联表来查到我们所需要的字段值。这时就可以通过以下两种方式,将多个查询合并在一起。
以RBAC所需要的五张表为例,如果需要查询某人具备的角色、权限,可通两张关联表来实现
select t1.username, t3.name as role_name, t5.name as permission_name
from i_users t1
left join i_user_roles_mapping t2 on t1.id = t2.user_name
left join i_roles t3 on t2.role_name = t3.id
left join i_role_permissions_mapping t4 on t3.id = t4.role_name
left join i_permissions t5 on t4.permission_name = t5.id
where t1.username = 'lisi'
但假设现在没有这两张mapping表,需要将以下三个查询合并成一个
select username from i_users where username = 'lisi';
select name as role_name from i_roles where id = '2';
select name as permission_name from i_permissions where id = '5';
如果用union all
是一列,不是一行
select username from i_users where username = 'lisi'
union all
select name as role_name from i_roles where id = '2'
union all
select name as permission_name from i_permissions where id = '5';
这时就可以用下面这两种方式
方式一
通过子查询的方式,如下:
select t1.username, t2.name, t3.name
from (select * from i_users where username = 'lisi') t1,
(select * from i_roles where id = '2') t2,
(select * from i_permissions where id = '5') t3;
方式二
使用with as
,如下:
with t1 as (
select * from i_users where username = 'lisi'
),
t2 as (
select * from i_roles where id = '2'
),
t3 as (
select * from i_permissions where id = '5'
)
select t1.username, t2.name as role_name, t3.name as permission_name from t1, t2, t3;
以上两种方式的查询效果,等同于前面的关联查询,如下: