系统城装机大师 - 固镇县祥瑞电脑科技销售部宣传站!

当前位置:首页 > 数据库 > Mysql > 详细页面

Mysql中常用的几种join连接方式总结汇总

时间:2022-05-08来源:www.pcxitongcheng.com作者:电脑系统城

目录
  • 1.内连接
  • 2.左连接
  • 3.右连接
  • 4.查询左表独有数据
  • 5.查询右表独有数据
  • 6.全连接
  • 7.查询左右表各自的独有的数据
  • 总结

1.首先准备两张表

部门表:

d0d974a8979311953540d70a289e2332.png

员工表:

1258156d80964119fbacf7f4a6787f2c.png

以下我们就对这两张表进行不同的连接操作

1.内连接

作用: 查询两张表的共有部分

语句:Select from tableA A Inner join tableB B on A.Key = B.Key

示例:SELECT * from employee e INNER JOIN department d on e.dep_id = d.id;

结果显示:通过这个查找的方法,我们没有查到id为8的数据

e80f31088c5aa791949c1bb62deec668.png

2.左连接

作用:把左边表的内容全部查出,右边表只查出满足条件的记录

语句:Select from tableA A Left Join tableB B on A.Key = B.Key

示例:SELECT * from employee e LEFT JOIN department d on e.dep_id = d.id;

结果显示:

76323cba2abd9453f769db4470a233c6.png

3.右连接

作用:把右边表的内容全部查出,左边表只查出满足条件的记录

语句:Select from tableA A Left Join tableB B on A.Key = B.Key

示例:SELECT * from employee e RIGHT JOIN department d on e.dep_id = d.id;

结果显示:

34066aa04f51cd6e5c477827f893921b.png

4.查询左表独有数据

作用:查询A的独有数据

语句:Select from tableA A Left Join tableB B on A.Key = B.Key where B.key IS NULL

示例:SELECT * from employee e LEFT JOIN department d on e.dep_id = d.id WHERE d.id IS NULL;

结果显示:

f0dd519be53c7f69a3d3ac874a0caa85.png

5.查询右表独有数据

作用:查询B的独有数据

语句:Select from tableA A Right Join tableB B on A.Key = B.Key where A.key IS NULL

示例:SELECT * from employee e RIGHT JOIN department d on e.dep_id = d.id WHERE e.id IS NULL;

结果显示:

025414646aec4dd3136847b0eba4bf5e.png

6.全连接

作用:查询两个表的全部信息

语句:Select from tableA A Full Outter Join tableB B on A.Key = B.Key

注:Mysql 默认不支持此种写法 Oracle支持       可以使用将左连接与右连接结合起来作为全连接

示例:

1
2
3
SELECT * from employee e LEFT JOIN department d on e.dep_id = d.id
UNION
SELECT * from employee e RIGHT JOIN department d on e.dep_id = d.id

结果显示:

dfcec7a6ffe337dc488b946476f3cab8.png

7.查询左右表各自的独有的数据

作用:查询A和B各自的独有的数据

语句:Select from tableA A Full Outter Join tableB B on A.Key = B.Key where A.key = null or B.key=null

示例:

1
2
3
SELECT * from employee e LEFT JOIN department d on e.dep_id = d.id WHERE d.id is NULL
UNION
SELECT * from employee e RIGHT JOIN department d on e.dep_id = d.id WHERE e.dep_id is NULL

结果显示:

98d4622d4ecf409d325d19ec4dd6a0ac.png

总结

到此这篇关于Mysql中常用的几种join连接方式的文章就介绍到这了

分享到:

相关信息

系统教程栏目

栏目热门教程

人气教程排行

站长推荐

热门系统下载