zoukankan      html  css  js  c++  java
  • SQL with as

    姓名    课程    分数
    张三    语文    74
    张三    数学    83
    张三    物理    93
    李四    语文    74
    李四    数学    84
    李四    物理    94

    先看下面一个嵌套的查询语句

    select * from tb where 分数 in (select 分数 from tb where 分数>90)

    上面的查询语句使用了一个子查询。虽然这条SQL语句并不复杂,但如果嵌套的层次过多,会使SQL语句非常难以阅读和维护。因此,也可以使用表变量的方式来解决这个问题,SQL语句如下:

    declare @t table (分数 int)
    insert into @t (分数) (select 分数 from tb where 分数>90)
    select * from tb where 分数 in (select * from @t)

    虽然上面的SQL语句要比第一种方式更复杂,但却将子查询放在了表变量@t中,这样做将使SQL语句更容易维护,但又会带来另一个问题,就是性能的损失。由于表变量实际上使用了临时表,从而增加了额外的I/O开销,因此,表变量的方式并不太适合数据量大且频繁查询的情况。为此,在SQL Server 中提供了另外一种解决方案,这就是公用表表达式(CTE),使用CTE,可以使SQL语句的可维护性,同时,CTE要比表变量的效率高得多。

    with cr as 
    (
        select 分数 from tb where 分数>90
    )
    select * from tb where 分数 in (select * from cr)

    在使用CTE时应注意如下几点:
    1. CTE后面必须直接跟使用CTE的SQL语句(如select、insert、update等),否则,CTE将失效。如下面的SQL语句将无法正常使用CTE:

    with cr as 
    (
        select 分数 from tb where 分数>90
    )
    select * from tb --应将这条SQL语句去掉
    select * from tb where 分数 in (select * from cr) --使用CTE的SQL语句应紧跟在相关的CTE后面

    2. CTE后面也可以跟其他的CTE,但只能使用一个with,多个CTE中间用逗号(,)分隔,如下面的SQL语句所示

    with cr1 as
    (
        select * from tb 
    ),
    cr2 as
    (
        select * from tb 
    ),
    cr3 as
    (
        select * from tb 
    )
    select a.* from cr1 a, cr2 b, cr3 c where a.分数 = b.分数 and a.分数 = c.分数

    3. 如果CTE的表达式名称与某个数据表或视图重名,则紧跟在该CTE后面的SQL语句使用的仍然是CTE,当然,后面的SQL语句使用的就是数据表或视图了,如下面的SQL语句所示:

    with tb as
    (
        select Name from Student 
    )
    select * from tb 

    4. 如果将 CTE 用在属于批处理的一部分的语句中,那么在它之前的语句必须以分号结尾,如下面的SQL所示:

    declare @t table (分数 int)
    insert into @t (分数) (select 分数 from tb where 分数>90);--必须加分号
    with tr as
    (
        select 分数 from tb where 分数 in (select * from @t)
    )
    select * from tr
  • 相关阅读:
    数据库操作语句大全(sql)
    尚未在 Web 服务器上注册ASP.NET 4.5。安装VS15后的问题(转)
    ASP.NET通过http/https的POST方式,发送和接受XML文件内容(转)
    C# 的关键字详细介绍(转)
    12个css高级技巧.html
    CentOS上安装elasticsearch
    springboot例子
    ajax的XmlHttpRequest对象常用方法
    阿里云oss操作
    Python出现Could not find a version that satisfies the requirement openpyxl (from versions: )
  • 原文地址:https://www.cnblogs.com/lgxlsm/p/3409639.html
Copyright © 2011-2022 走看看