树状图两种方法:1.递归(不需要管几级表)
2.自链接(知道几级表)
性能问题:因为只连接一次数据库,所以递归性能很高,推荐8以后用递归
格式
with recursive [新表名称-例:t1] as {
selecte * from [要查询的表名-例:course_category] where id='1'
//union all 连接 会把查询到的结果放入t1 表 也就是递归出来的t1 表
union all
selecte * from [查询的表-例:course_category] inner join t1 on t1.id = course_category.parentid
}
select * form t1
例
with recursive t1 as (
select * from course_category where id='1'
union all
//注意起别名 前面的 * 也要用别名查 t2.*
select t2.* from course_category t2 inner join t1 on t1.id = t2.parentid
)
select * from t1
order by t1.id