添加别名的重要性

-- =============================================
-- 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


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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值