现有两张表t_tree(树)和fa(方案)
t_tree表结构为

fa表结构为

两张表数据(左为t_tree,右为fa)如下:
表数据更直观的图展现如下

现需要求得各个节点的方案,节点没有方案的取最近的父节点的方案。最后查询结果类似于如下

查询结构类似于

需要怎么解? 需要一个SQL方案
现有两张表t_tree(树)和fa(方案)
t_tree表结构为
fa表结构为
两张表数据(左为t_tree,右为fa)如下:
表数据更直观的图展现如下
现需要求得各个节点的方案,节点没有方案的取最近的父节点的方案。最后查询结果类似于如下
查询结构类似于
需要怎么解? 需要一个SQL方案
一张表即可
pid , 根的pid指向自己
试下 connect by,oracle结构化查询。
结贴,自己写出来了:
select id, fid, root_id, faid from (select id, fid, root_id, faid, lvl, min(lvl) over(partition by id) min_lvl from (
select id, fid, root_id, (select tr.fa from t_tree tr where tr.id = t.root_id) faid, lvl from (
select id, fid, connect_by_root(id) root_id, fa, level lvl from t_tree connect by prior id = fid
) t
)
where faid is not null
order by id, lvl
)
where lvl = min_lvl
引用来自“StormFour”的答案
结贴,自己写出来了:
select id, fid, root_id, faid from (select id, fid, root_id, faid, lvl, min(lvl) over(partition by id) min_lvl from (
select id, fid, root_id, (select tr.fa from t_tree tr where tr.id = t.root_id) faid, lvl from (
select id, fid, connect_by_root(id) root_id, fa, level lvl from t_tree connect by prior id = fid
) t
)
where faid is not null
order by id, lvl
)
where lvl = min_lvl
connect by 这种只能自己写.
问别人比自己写更难
其实不只是Oracle,DB2也支持递归查询。
用with 语句可以写出来。。