需求背景:项目中,对一张商品分类的表需要查询当前分类节点及父节点。
关系对应:id-》root_id
Mysql
WITH RECURSIVE cae AS (
SELECT id, id AS root_id
FROM table WHERE parentid IS NULL
UNION ALL
SELECT t.id, category.root_id FROM table t
inner JOIN category ON t.parentid = category.id
) SELECT * FROM cae
在mysql中就使用 with recursive 函数,注意搭配root_id,保留根节点的ID。
Oracle
在oracle中跟mysql有所不同,oracle使用的start with ... connect by ... 子句实现。
select [level],*
from table
start with condition1
connect by [nocycle] prior condition2
where condition3 order by [sibilings] 排序
Tip:
- start with ,根节点数据
- connect by [prior] id = parentid 连接条件,目的就是给出父子之间的关系
- 对proir说明:
- connect by prior id=parentid 采用自上而下的递归方式
- connect by id=prior parentid 采用自下而上的递归方式
- level关键字,用于表示树的层次
- connect_by_root 方法,能够获取第一层根节点的任意字段值