sqlite 使用 cte 及 递归的实现示例

1.多级 cte 查询示例。

with cte as
(
   select pageid 
   from cm_bookpage
) , cte2 as
(
  select pageid, 2 as content from cte
)
select * from cte2

2. cte 递归查询文章标题层级,3872某一叶子节点,要查询出所有上级目录并排序返回。

with cte as
(
  select pageid,bookid,title,parentpageid,1 as orderid
  from cm_bookpage 
  where pageid = 3872        
  union all  
  select a.pageid,a.bookid,a.title,a.parentpageid,(cte.orderid+1) as orderid
  from cm_bookpage a  
    inner join cte       
      on a.pageid = cte.parentpageid  
)
select *
from cte
order by orderid desc 

 

转载于:https://www.cnblogs.com/nanfei/p/9030034.html

你可能感兴趣的:(数据库)