zoukankan      html  css  js  c++  java
  • SQL数据库CTE的用法

    在很多编程语言中都有 for循环这样的东西。在数据库里面 替代他是 游标

    但是游标使用起来是相当耗费资源的,今天看见一个CTE尝试了下他的用法

    create table employewhere
    (
     id int identity(1,1),
     [name] varchar(10),
     [value] varchar(10),
     [ttime] int
    )

    insert employewhere
    select '张三',2,1
    union all
    select '张三',2,2
    union all
    select '张三',2,3
    union all
    select '张三',2,4
    union all
    select '李四',2,1
    union all
    select '李四',2,2
    union all
    select '李四',2,3
    union all
    select '李四',2,4
    union all
    select '李四',2,1

    insert employewhere
    select '王五',2,1
    union all
    select '王五',2,3
    union all
    select '王五',2,4

    我想得到ttime为连续数字的name

    张三

    李四

    select * from  employewhere

    1 张三 2 1
    2 张三 2 2
    3 张三 2 3
    4 张三 2 4
    5 李四 2 1
    6 李四 2 2
    7 李四 2 3
    8 李四 2 4
    9 王五 2 1
    10 王五 2 3
    11 王五 2 4
    12 王五 2 1
    13 王五 2 3
    14 王五 2 4
    15 王五 2 1
    16 王五 2 3
    17 王五 2 4

    -----------------------------

    with myCTE as
    (
     select id,[name],value,ttime ,1 as number   from employewhere where value=2
     union all
     select tt.id,tt.name,tt.value,tt.ttime ,number+1 from employewhere as tt
     inner join myCTE on myCTE.[name]=tt.[name] and tt.ttime=myCTE.ttime+1--连接起来的条件
     where tt.value=2
    )
    select * from myCTE where number>3

    8 李四 2 4 4
    4 张三 2 4 4

    但是为什么要这么写呢

    我们可以这么执行查询里面的数据

    with myCTE as
    (
     select id,[name],value,ttime ,1 as number   from employewhere where value=2
     union all
     select tt.id,tt.name,tt.value,tt.ttime ,number+1 from employewhere as tt
     inner join myCTE on myCTE.[name]=tt.[name] and tt.ttime=myCTE.ttime+1--连接起来的条件
     where tt.value=2
    )
    select * from myCTE

    可以得到数据

    1 张三 2 1 1
    2 张三 2 2 1
    3 张三 2 3 1
    4 张三 2 4 1
    5 李四 2 1 1
    6 李四 2 2 1
    7 李四 2 3 1
    8 李四 2 4 1
    9 王五 2 1 1
    10 王五 2 3 1
    11 王五 2 4 1
    12 王五 2 1 1
    13 王五 2 3 1
    14 王五 2 4 1
    15 王五 2 1 1
    16 王五 2 3 1
    17 王五 2 4 1
    11 王五 2 4 2
    14 王五 2 4 2
    17 王五 2 4 2
    11 王五 2 4 2
    14 王五 2 4 2
    17 王五 2 4 2
    11 王五 2 4 2
    14 王五 2 4 2
    17 王五 2 4 2
    8 李四 2 4 2
    7 李四 2 3 2
    8 李四 2 4 3
    6 李四 2 2 2
    7 李四 2 3 3
    8 李四 2 4 4
    4 张三 2 4 2
    3 张三 2 3 2
    4 张三 2 4 3
    2 张三 2 2 2
    3 张三 2 3 3
    4 张三 2 4 4

    是不是发现很多重复数据 同时可以更直观的让我们认识 其实 CTE本身就是一个临时表这样的一个东西 只是不要你进行创建

    最后面一排 使我们写的 number

    然后我们在进行筛选

    where number>3

    就是排序中连续有三个的

    于是就把 我们

    张三和李四查询出来了

  • 相关阅读:
    考研讲座笔记——张雪峰
    【极简版】OpenGL 超级宝典(第五版)环境配置 VS2010
    OpenGL编程指南(第九版) Tiangles 学习笔记
    qt学习笔记
    郑州大学2018新生训练赛第十场题解
    Win10 中将网页转换成pdf的简便方法
    Kali Linux ——在无网络情况下安装无线网卡驱动
    成环的概率dp(初级) zoj 3329
    概率dp的边界处理 POJ 2096
    node连接mysql生成接口,vue通过接口实现数据的增删改查(一)
  • 原文地址:https://www.cnblogs.com/dingdingmao/p/3146538.html
Copyright © 2011-2022 走看看