首页 > 数据库技术 > 详细

mysql中的几种join 及 full join问题

时间:2019-02-13 10:15:33      阅读:197      评论:0      收藏:0      [点我收藏+]

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

初始化SQL语句:

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

1、笛卡尔积

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

mysql> select * from t1 join t2;
  • 1

技术分享图片

2、左连接

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

技术分享图片

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

技术分享图片

3、右连接

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

技术分享图片

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

技术分享图片

4、内连接

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

技术分享图片

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

技术分享图片

5、左表独有

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

技术分享图片

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

技术分享图片

6、右表独有

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

技术分享图片

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

技术分享图片

7、全连接

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

技术分享图片

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
  • 2
  • 3
  • 技术分享图片

8、并集去交集

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

技术分享图片

  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;
  • 1
  • 2
  • 3

技术分享图片

mysql中的几种join 及 full join问题

原文:https://www.cnblogs.com/wuer888/p/10368176.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!