SQL Join 的七大模式

215 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第1天,点击查看活动详情

写作目的

目前在看一些mysql 相关的教学视频所以简单记录一下觉得有必要记录的内容。

Join

mysql 使用join来联合多表的查询,主要在mysql 中就分为

  • inner join : 获取两个表中字段匹配关系的记录信息。
  • left join : 获取左表所有记录,及时右边中没有记录也会将左表的查询查出来。
  • right join : 与left 相反,用于获取右表的记录 即使 左表没有对应的匹配的记录。

7种join 的实现

首先给一个全部的图(ps:忽略自己画图丑)

image.png

inner join

数据交集内连接 image.png

select <select condition> from a inner join b on a.key=b.key

left join

左连接

标准 4 左表加交集

image.png

select <select condition> from a left join b on a.key=b.key

变化 2 单独 左表

image.png

select <select condition> from a left join b on a.key=b.key where b.key is null

right join

数据右连接

标准 5 右表交集

image.png

select <select condition> from a right join b on a.key=b.key

变化 3 单独 右表

image.png

select <select condition> from a right join b on a.key=b.key where a.key is null

oracle 支持的 full outer join

标准 7 获取所有的数据

image.png

select <select condition> from a full outer join b on a.key=b.key 

变化 6 不包含交集部分数据

image.png

select <select condition> from a full outer join b on a.key=b.key where a.key is null or b.key is null

union

合并两个数据集合的数据

这里引申一下 union 的使用

  • union 连接两个数据集合 两个集合的列数一定得一样不然会报错 列数不一致
  • union后字段的名称以第一条SQL为准
  • union 会自动将重复的数据值进行摒弃 所以下面的考虑中 4+3 可以为 标准 right + left
  • union 数据 如果想要看重复的数据 可以使用 all union

7 在mysql中 union 实现 比如说 4+3 之类的

image.png

select <select condition> from a left join b on a.key=b.key
union
select <select condition> from a right join b on a.key=b.key where a.key is null 

6 在mysql中 union 实现 比如上面的 2+3

image.png

select <select condition> from a left join b on a.key=b.key where b.key is null
union
select <select condition> from a right join b on a.key=b.key where a.key is null