• CTE表达式递归


    /*通用表表达式 CTE的递归*/
    --1.CTE有一个优点就是可以允许自身引用,这样可以方便创建递归的CTE
    --递归CTE的结构包括:定位点成员和递归成员,递归的过程就是Ti作为输入,Ti+1作为输出。
    --创建测试数据
    create table test(
    id varchar(30),
    parentID varchar(30),
    name varchar(30)
    )
    insert into test values('001','','1');
    insert into test values('001001','001','11');
    insert into test values('001002','001','12');
    insert into test values('001001001','001001','111');
    insert into test values('001001002','001002','112');
    insert into test values('001001001001','001001001','1111');
    --查询11的下级
    with c11 as
    (
    select * from test where id='001001'--定位点成员,作为Ti输入,查询它的下级就是 c11.id=test.ParentID
    union all--必须以union all 来连接递归成员
    select b.* from c11 a join test b on a.id=b.ParentID--必须是b.*,a.*报错了,无限循环了
    )
    select * from c11 order by id;
    --结果:
    001001	001	11
    001001001	001001	111
    001001001001	001001001	1111
    --查询1111的上级
    
    with c1111 as
    (
    select * from test where id='001001001001'--定位点成员,座位图T0输入,查询它的上级就是 c1111.ParentID=test.ID
    union all
    select b.* from c1111 a join test b on a.parentid=b.id
    )
    select * from c1111 order by id;
    --结果集:
    001		1
    001001	001	11
    001001001	001001	111
    001001001001	001001001	1111
    

      

  • 相关阅读:
    防止IE缓存jquery ajax 内容
    MyBatis中主要类的生命周期和应用范围
    MyBatis学习练习
    MySql 日期格式化函数date_format()
    getFields()和getDeclaredFields()
    Java final修饰形参
    随笔
    Java SSH远程执行Shell脚本实现(转)
    jQuery 属性操作
    [git]解决:git config --global push.default matching
  • 原文地址:https://www.cnblogs.com/niuge/p/2649516.html
Copyright © 2020-2023  润新知