MSSQL示例(五)left join on与where的执行次序与影响

— =============================================

— Author:tomtom– Create date: 2015.3.4– Description:left join on与where的执行次序与影响– =============================================

/*

在看结论之前,可以先准备数据后,查看示例2.3的语句自己想一下结果,实际执行一下,可以带着问题看

结论1:先left join on 后where,where是对left join on执行完成后的结果做筛选;

结论2:算法过程按个人推理应该是:1)on条件在左表右表各自筛选行;2)根据on左右联接;3)补齐保证左表所有行都出现结论3:对于left,不管on中怎样的条件,左边表的所有行都会出现,on只在显示左表所有行的基础上影响联接结果。

*/–1.准备数据create table t1(id1 int,name1 varchar(50))gocreate table t2(id2 int,name2 varchar(50))goselect * from t1select * from t2insert into t1select 1,’1′ union allselect 11,’11’ union allselect 12,’12’ union allselect 13,’13’insert into t2select 1,’21’ union allselect 11,’211′ union allselect 12,’22’ union allselect 12,’222′ union allselect 23,’23’select * from t1left join t2 on t1.id1=t2.id2/*2.1示例—左表t1所有行都在,右表t2.id2=1的有数据,其他为空*/select * from t1left join t2 on t1.id1=t2.id2 and t2.id2=1/*2.2示例—left join on关联后,,where对其结果做筛选*/select * from t1left join t2 on t1.id1=t2.id2where t2.id2=1/*2.3示例

下例左表t1.id1=11所有行还会出现;下例具体算法过程是:1)t1.id1=11筛选左表(只剩一行);2)根据t1.id1=t2.id2左右联接,去掉无关联的行(只剩一行);3)补齐(补空行)*/select * from t1left join t2 on t1.id1=t2.id2 and t1.id1=11/*2.4示例*/select * from t1left join t2 on t1.id1=t2.id2 and t1.id1=12–where t2.id2=1 –left join on后id1=1这一行的id2是NULL,where是对left join on的结果筛选,因此结果是没有任何行/*2.5示例*/select * from t1left join t2 on t1.id1=t2.id2where t1.id1=12

每个人在他的人生发轫之初,总有一段时光,

MSSQL示例(五)left join on与where的执行次序与影响

相关文章:

你感兴趣的文章:

标签云: