首先创建两张表,一个student_table,一个salary。表名起的不是合乎情景,就这样吧。

  1. use mysql;
  2. create table student_table(
  3. id varchar(25),
  4. name varchar(25),
  5. brith varchar(25),
  6. sex varchar(25)
  7. );
  8. insert into student_table
  9. values
  10. ('1004' , '张三' ,'2000-08-06' , '男'),
  11. ('1009' , '李四', '2000-01-01', '男'),
  12. ('1010' , '李四', '2001-01-01', '男'),
  13. ('1006' , '王五', '2000-08-06' , '女'),
  14. ('1008' , '张三', '2002-12-01', '女'),
  15. ('1012' , '张三', '2001-12-01', '女'),
  16. ('1011' , '李四', '2002-08-06' , '女'),
  17. ('1013' , '赵六' ,'2000-09-06' , '男');
  18. create table salary(
  19. sid varchar(25),
  20. department varchar(25),
  21. salary int(10)
  22. );
  23. insert into salary
  24. values
  25. ("1004","后勤",10000),
  26. ("1009","行政",11000),
  27. ("1011","研发",19000),
  28. ("1010","后勤",9000),
  29. ("1013","研发",25000),
  30. ("1006","销售",15000),
  31. ("1012","研发",6000);

创建的两个表
image.png
image.png

内连接

现在我要进行一个内连接查询

  1. select a.*,b.* from student_table a inner join salary b on a.id = b.sid; -- 内连接

得到的查询结果是
image.png
可以发现这个查询的显示就是根据id 和 sid 进行匹配,如果有匹配的值,那么就会连接到一行,作为结果,如果id和sid有出现不匹配的项的话,不会进行返回结果。

左连接

那么现在进行一个左连接

  1. select a.*,b.* from student_table a left join salary b on a.id = b.sid; -- 左连接

得到的结果是

image.png

你会发现左连接left 左边表的所有字段都会保留都会保留,即使存在没有匹配到的数据。而left右边的表数据没有匹配到左边表的数据就会被设为null。也就是说这样的连接是已left左边的表为基准。

右连接

相对的右连接,那就是按照右边的表进行匹配。

  1. select a.*,b.* from student_table a right join salary b on a.id = b.sid; -- 右连接

image.png
注意我右边表的sid在左边表是完全可以匹配到的,所以这里不会出现空。按照右边为基础,左边
多余的id对应的数据是不会显示的。要的是匹配的数据,右表的数据都可以匹配上,所以不会出现null。

你注意到的可能是表中有两个王五,但是这里也不影响,毕竟工资和部门是不一样的。所以不要认为是冗余的数据哦。

全连接

这不是有手就行?全连接当然就是左连接和右连接的结合啦。

本来的代码

  1. select a.*,b.* from student_table a full join salary b on a.id = b.sid;

但是mysql 8的版本还没有被支持,所以我们可以这样去实现全连接

  1. select a.*,b.* from student_table a left join salary b on a.id = b.sid union select a.*,b.* from student_table a right join salary b on a.id = b.sid;

image.png
这样你会想,那这样不是和左连接的效果一样吗?是的,效果是一样的,但是其实是不一样的,左连接会以左表为基准,左边表的数据都会显示,没有匹配到的数据会被设置为null。全连接会全部作为基准,相对的没有匹配到的也会同样的设置为null,但是我们的salary作为基准的时候左表是完全匹配的,所以不会出现null。

那么现在在salary添加一个条数据,让student_table没有的数据。然后再次进行一次全连接查询。

  1. insert into salary values(10086,"安全",18000);

salary 表

image.png
student_table 表是没有变

image.png

ok ,再次运行全连接代码

  1. select a.*,b.* from student_table a left join salary b on a.id = b.sid union select a.*,b.* from student_table a right join salary b on a.id = b.sid;

image.png
你看这样就非常形象的说明了。

再来看一张图,分别对应内连接,左连接,右连接,全连接。完完全全明白。
image.png

语雀这个太好用了。感觉非常丝滑,这个用来写笔记。本来是作为笔记,还是按照博客的文章模式来写了。