sql中的几种join 及 full join问题

【注意】:Oracle数据库支持full join,mysql是不支持full join的,但仍然可以同过左外连接+ union+右外连接实现
初始化SQL语句:

/*join 建表语句*/
drop database if exists test;
create database test;
use test;
 
/* 左表t1*/
drop table if exists t1;
create table t1 (id int not null,name varchar(20));
insert into t1 values (1,'t1a');
insert into t1 values (2,'t1b');
insert into t1 values (3,'t1c');
insert into t1 values (4,'t1d');
insert into t1 values (5,'t1f');
 
/* 右表 t2*/
drop table if exists t2;
create table t2 (id int not null,name varchar(20));
insert into t2 values (2,'t2b');
insert into t2 values (3,'t2c');
insert into t2 values (4,'t2d');
insert into t2 values (5,'t2f');
insert into t2 values (6,'t2a');

1、笛卡尔积

两表关联,把左表的列和右表的列通过笛卡尔积的形式表达出来。

mysql> select * from t1 join t2;

在这里插入图片描述

2、左连接

两表关联,左表全部保留,右表关联不上用null表示。

在这里插入图片描述

mysql> select * from t1 left join t2 on t1.id = t2.id;

在这里插入图片描述

3、右连接

右表全部保留,左表关联不上的用null表示。
在这里插入图片描述

mysql> select * from t1 right join t2 on t1.id =t2.id;

在这里插入图片描述

4、内连接

两表关联,保留两表中交集的记录。
在这里插入图片描述

mysql> select * from t1 inner join t2 on t1.id = t2.id;

这里写图片描述

5、左表独有

两表关联,查询左表独有的数据。
在这里插入图片描述

mysql> select * from t1 left join t2 on t1.id = t2.id where t2.id is null;

这里写图片描述

6、右表独有

两表关联,查询右表独有的数据。
这里写图片描述

mysql> select * from t1 right join t2 on t1.id = t2.id where t1.id is  null;

这里写图片描述

7、全连接

两表关联,查询它们的所有记录。
这里写图片描述
oracle里面有full join,但是在mysql中没有full join。我们可以使用union来达到目的。

mysql> select * from t1 left join t2 on t1.id = t2.id
    -> union 
    -> select * from t1 right join t2 on t1.id = t2.id;

在这里插入图片描述
在hive中可以直接使用full join解决问题,但是在同一层级的查询中不可连续多次使用full join否则会出现问题,如果需要多次使用full join建议在不同层级中使用,实例如下:

select * 
from t1
full join t2
on t1.user_id = t2.user_id

8、并集去交集
两表关联,取并集然后去交集。
在这里插入图片描述

mysql> select * from t1 left join t2 on t1.id = t2.id where t2.id is null
    -> union 
    -> select * from t1 right join t2 on t1.id = t2.id where t1.id is null;

在这里插入图片描述

  • 20
    点赞
  • 151
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

扫地增

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值