查询以列出嵌套结果

时间:2016-01-26 19:10:59

标签: sql nested

我有3张桌子

t_role
t_role_access_id
t_access

t_role

**id   NAME**

90   Dep1
91   Tes1
92   Bes1 

t_role_access_id

**role_id   acc_type acc_id**

90        role       91
91        access     103
91        access     105
92        access     102

t_access

**id     name application**

100    Read        App1
101    Modify      App2
102    Read        App1
103    Write       App2
104    Read        App3
105    Modify      App3

当我运行以下查询时,我得到类似下面的输出

select * from t_role_access_id trai
left join t_access ta on ta.id=trai.acc_id
left join t_role tr on tr.id=trai.ROLE_ID
where tr.id=90


**role_id,   acc_type, acc_id, id, name, application ,id ,  NAME**
    90        role       91                         90   Dep1

我需要的是这样的事情。查询应检查acc_type是否类似于“role”,然后再返回“t_role_access_id”表并获取详细的访问详细信息

**role_id,   acc_type, acc_id, id, name, application ,id ,  NAME**
90        role       91                             90   Dep1
91        access     103   103    Write       App2  90   Dep1
91        access     105   105    Modify      App3  90   Dep1   

这只是一个例子。我的角色嵌套在不同深度级别的角色中。所以我需要编写一个查询来获取granuall细节。任何帮助都非常感谢。

1 个答案:

答案 0 :(得分:0)

进行另一次加入是不够的,比如这样,在tmp1和tmp2中你可以根据需要过滤或分组(或其他)吗?

select tmp1.* , tmp2.* from
(
select 
tr.id as tr_id, tr.name as tr_name, 
trai.role_id, trai.acc_type, trai.acc_id,
ta.id, ta.name, ta.application
from t_role_access_id trai
left join t_access ta on ta.id=trai.acc_id
left join t_role tr on tr.id=trai.ROLE_ID
-- where tr.id=90
) as tmp1

left join
(
select trai2.role_id as det_role_id, trai2.acc_type as det_type, trai2.acc_id as det_acc_id
from t_role_access_id as trai2 
-- where acc_type = 'role'
) as tmp2

on tmp2.det_acc_id = tmp1.acc_id