SQL left/right join

记一下left/right join中,使用不同条件的不同结果。

测试表:
create table yan_test1 ( id int,test VARCHAR(20))
create table yan_test2 ( id int,test VARCHAR(20))

Query1

select a.*, b.*
from yan_test1 a, yan_test2 b
where a.id = b.id (+)
------------------------
1 test_string 1 test_string
2 test_string null null

Query2

select a.*, b.*
from yan_test1 a, yan_test2 b
where a.id = b.id (+)
and b.id > 0 -- 相当于inner join
------------------------
1 test_string 1 test_string

Query3

select a.*, b.*
from yan_test1 a, yan_test2 b
where a.id = b.id (+)
and b.id (+) > 0 -- 依然是right join,但结果和query1相同。
------------------------
1 test_string 1 test_string
2 test_string null null

Query4

select a.*, b.*
from yan_test1 a, yan_test2 b
where a.id = b.id (+)
and b.id (+) > 1 -- 也就是说b.id (+)依然会返回所有行,但不符合该条件的则返回null。
------------------------
1 test_string null null
2 test_string null null

双join条件

create table yan_test1 ( id1 int, id2 int,test VARCHAR(20));
create table yan_test2 ( id1 int, id2 int,test VARCHAR(20));

select * from yan_test1;
-----------
1	1	dfs
2	1	dfs
3	1	dfs

select * from yan_test2;
-----------
1	1	dfs
2	1	dfs
2	2	dfs
4	1	dfs

select a.*, b.*
from yan_test1 a, yan_test2 b
where a.id1 = b.id1 (+)
-----------
1	1	dfs	1	1	dfs
2	1	dfs	2	1	dfs
2	1	dfs	2	2	dfs
3	1	dfs null null null

select a.*, b.*
from yan_test1 a, yan_test2 b
where a.id1 = b.id1 (+)
and a.id2 = b.id2 (+) -- 双连接条件
-----------
1	1	dfs	1	1	dfs
2	1	dfs	2	1	dfs -- 因此对于那些连接成功的rows,需要同时满足两个连接条件
3	1	dfs null null null					

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值