【注意】:Oracle數據庫支持full join,mysql是不支持full join的,但仍然可以同過左外連接+ union+右外連接實現
初始化SQL語句:
-
/*join 建表語句*/
-
drop database if exists test;
-
create database test;
-
use test;
-
-
/* 左表t1*/
-
drop table if exists t1;
-
create table t1 (id int not null,name varchar(20));
-
insert into t1 values (1,'t1a');
-
insert into t1 values (2,'t1b');
-
insert into t1 values (3,'t1c');
-
insert into t1 values (4,'t1d');
-
insert into t1 values (5,'t1f');
-
-
/* 右表 t2*/
-
drop table if exists t1;
-
create table t2 (id int not null,name varchar(20));
-
insert into t2 values (2,'t2b');
-
insert into t2 values (3,'t2c');
-
insert into t2 values (4,'t2d');
-
insert into t2 values (5,'t2f');
-
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來達到目的。
-
mysql> select * from t1 left join t2 on t1.id = t2.id
-
-> union
-
-> select * from t1 right join t2 on t1.id = t2.id;
- 1
- 2
- 3
8、並集去交集
兩表關聯,取並集然后去交集。
-
mysql> select * from t1 left join t2 on t1.id = t2.id where t2.id is null
-
-> union
-
-> select * from t1 right join t2 on t1.id = t2.id where t1.id is null;
- 1
- 2
- 3