Home > Database > Mysql Tutorial > 有意思的left join语句

有意思的left join语句

WBOY
Release: 2016-06-07 14:53:35
Original
1229 people have browsed it

有意思的left join语句 问题的初衷是,在一个SQL语句中,有left join, 我加条件在where后面发生死锁,于是想是否可以把条件加入到left join的on后面? www.2cto.com 也就是下面两个语句是否效果一样: 语句1: select t1.*,t2.* from t1 left join t2 on t1


有意思的left join语句

 

问题的初衷是,在一个SQL语句中,有left join, 我加条件在where后面发生死锁,于是想是否可以把条件加入到left join的on后面?  www.2cto.com  

也就是下面两个语句是否效果一样:

语句1: select t1.*,t2.* from t1 left join t2 on t1.id=t2.id and t1.feild=1

 

语句2: select t1.*,t2.* from t1 left join t2 on t1.id=t2.id where t1.feild=1

 

数据环境:

create table t1(id int, feild int);

insert into t1 values(1 , 1);

insert into t1 values(1 , 2);

insert into t1 values(1 , 3);

insert into t1 values(1 , 4);

insert into t1 values(2 , 1);

insert into t1 values(2 , 2);

create table t2(id int, feild int);

insert into t2 values(1 , 1);

insert into t2 values(1 , 2);

insert into t2 values(1 , 5);

insert into t2 values(1 , 6);

insert into t2 values(2 , 1);

insert into t2 values(2 , 3);

 

经过验证发现: 语句1可以这样来理解,把left join 的on后面的所有条件看成一个整体,这里就是t1.id=t2.id and t1.feild=1看成一个整体,坐连接的时候,串t2表,看是否有满足条件的记录,如果没有就串null值。

语句2的理解简单了,现在left join,在最后结果集中做where过滤

 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template