zoukankan      html  css  js  c++  java
  • 添加别名的重要性

    -- =============================================
    -- Author:            <Author,,CC>
    -- Create date:        <Create Date,, 2014-06-29 12:25:20.010>
    -- Description:        <Description,,加别名的重要性>
    -- Environment:        <Version,, Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64))>
    -- =============================================
    
    use test
    go
    
    create table t1(
    id int ,
    id1 int
    )
    
    create table t2(
    id11 int,
    id2 int
    )
    
    insert into t1(id ,id1)
    select 1,2 union all
    select 2,3 union all
    select 3,4 union all
    select 4,5 union all
    select 5,5
    
    insert into t2(id11,id2) 
    select 1,2 union all
    select 2,3
    
    create table t3(
    id int,
    id2 int
    ) 
    insert into t3(id,id2) 
    select 1,2 union all
    select 2,3
    
    -- 1.查询t1表中的id在t3中的记录,没有别名,记录正确
    select * from t1 a 
    where id in (select id from t3 b)  
    
    --2. 假如in的内查询中不存在外查询的列
    select * from t1 a
    where id in (select id from t2 b)
    /*
    此时我们可以看到语句并没有错,而是会去寻找t1中的数据,语句结果同下面的查询效果:
    select * from t1 a 
    where id in (select a.id from t2)
    其实是内查询不存在,所以结果就自己去寻找外面的查询
    */
    
    --3. 我们把内表加上别名,此时才是我们要的结果,并且提示报错
    select * from t1 a
    where id in (select b.id from t2 b)
    
    --删除t2中的数据,再测试一下
    truncate table t2
    --3. t2中没有数据,此时则不会往外层寻找
    select * from t1 a 
    where id in (select a.id from t2)
    
    drop table t1,t2,t3


    以上结果只是查询,若换为删除出现这种情况则可能会把外表整个的数据删除掉,造成不能想象的问题,所以在允许的情况下尽量还是要把别名加上.

  • 相关阅读:
    递归函数底层原理浅析
    lambda expression & mutable
    命令mv
    printf的参数
    程序结构之静态本地变量
    汇编.align指令
    程序结构之全局变量
    命令touch
    更改gcc默认版本,实现gcc版本升降级
    命令chmod
  • 原文地址:https://www.cnblogs.com/zerocc/p/3814959.html
Copyright © 2011-2022 走看看