zoukankan      html  css  js  c++  java
  • 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
    

      

  • 相关阅读:
    迁移
    zendframework 2 链接数据库
    zendframework 2
    merge sort and quick sort 自己去理解吧
    ubuntu git 使用
    resumablejs 分块上传 断点续传
    video.js html5 视频播放器
    swfupload 例子
    php 润年 星期 天数
    ubuntu 安装 axel
  • 原文地址:https://www.cnblogs.com/niuge/p/2649516.html
Copyright © 2011-2022 走看看