添加別名的重要性

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


以上結果只是查詢,若換爲刪除出現這種狀況則可能會把外表整個的數據刪除掉,形成不能想象的問題,因此在容許的狀況下儘可能仍是要把別名加上.

測試

相關文章
相關標籤/搜索