【注:本文转自 https://blog.csdn.net/u012410733/article/details/63684663】

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

初始化SQL语句:

  1. /*join 建表语句*/
  2. drop database if exists test;
  3. create database test;
  4. use test;
  5. /* 左表t1*/
  6. drop table if exists t1;
  7. create table t1 (id int not null,name varchar(20));
  8. insert into t1 values (1,\'t1a\');
  9. insert into t1 values (2,\'t1b\');
  10. insert into t1 values (3,\'t1c\');
  11. insert into t1 values (4,\'t1d\');
  12. insert into t1 values (5,\'t1f\');
  13. /* 右表 t2*/
  14. drop table if exists t2;
  15. create table t2 (id int not null,name varchar(20));
  16. insert into t2 values (2,\'t2b\');
  17. insert into t2 values (3,\'t2c\');
  18. insert into t2 values (4,\'t2d\');
  19. insert into t2 values (5,\'t2f\');
  20. insert into t2 values (6,\'t2a\');

 

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

  1. mysql> select * from t1 join t2;

 这里写图片描述

 

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

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

这里写图片描述


这里写图片描述

 

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

这里写图片描述

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

 这里写图片描述

 

两表关联,保留两表中交集的记录。

这里写图片描述

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

 这里写图片描述

 

两表关联,查询左表独有的数据。

这里写图片描述

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

 这里写图片描述

 

两表关联,查询右表独有的数据。

这里写图片描述

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

 这里写图片描述

 

两表关联,查询它们的所有记录。

这里写图片描述

oracle里面有full join,但是在mysql中没有full join。我们可以使用union来达到目的。

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

 这里写图片描述

 

两表关联,取并集然后去交集。

这里写图片描述

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

 这里写图片描述

版权声明:本文为hong-bo原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/hong-bo/p/13278596.html