SQL语句理解左右连接和where

本文以左连接left join为例,详细讲解on和where子句在限制主表和从表条件时的不同作用。on后面的条件仅用于连接,不影响结果集,而where则在连接后对结果集进行筛选。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里以左连接 left join 为例,说明 on 后面的条件与 where 后面条件的区别

创建测试表:TAB_1、TAB_2

create table TAB_1 as (
	select 'c' as A,'d' as B,'3' as C,'4' as D from dual
	union all
	select 'a' as A,'b' as B,'1' as C,'2' as D from dual
	);
create table TAB_2 as (
	select 'c' as A,'d' as B,'2' as C,'4' as D from dual
	union all
	select 'a' as A,'b' as B,'1' as C,'3' as D from dual
	);

 1、在 on 里面限制从表

select * from TAB_1 M left join TAB_2 N 
on M.A=N.A and M.B=N.B
and N.C='1';

2、 在where里面限制从表

select * from TAB_1 M left join TAB_2 N 
on M.A=N.A and M.B=N.B
where N.C='1';

3、 在 on 里面限制主表

select * from TAB_1 M left join TAB_2 N 
on M.A=N.A and M.B=N.B
and M.C='1';

4、在 where 里面限制主表

select * from TAB_1 M left join TAB_2 N 
on M.A=N.A and M.B=N.B
where M.C='1';

5、在 on 里面同时限制主表和从表

select * from TAB_1 M left join TAB_2 N 
on M.A=N.A and M.B=N.B
and M.C='1'
and N.C='4';

 

select * from TAB_1 M left join TAB_2 N 
on M.A=N.A and M.B=N.B
and M.C='4'
and N.C='1';

 

6、在 on 里面限制从表,在where里面限制主表

select * from TAB_1 M left join TAB_2 N 
on M.A=N.A and M.B=N.B
and N.C='4'
where M.C='1';

select * from TAB_1 M left join TAB_2 N 
on M.A=N.A and M.B=N.B
and N.C='1'
where M.C='4';

 

7、在 on 里面限制主表,在 where 里面限制从表

select * from TAB_1 M left join TAB_2 N 
on M.A=N.A and M.B=N.B
and M.C='1'
where N.C='4';

select * from TAB_1 M left join TAB_2 N 
on M.A=N.A and M.B=N.B
and M.C='4'
where N.C='1';

总结:

通过以上实例,不难看出 on 后面的条件只会作为连接条件进行限定,并不影响结果集,结果集依然按照 left join 的特性进行输出。where 后面的条件是作为连接之后结果集的筛选 。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值