1. 程式人生 > 實用技巧 >mysql的幾種join 及 full join 問題

mysql的幾種join 及 full join 問題

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

【注意】: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 t2; 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、笛卡爾積

兩表關聯,把左表的列和右表的列通過笛卡爾積的形式表達出來。

mysql> select * from t1 join t2;

2、左連線

兩表關聯,左表全部保留,右表關聯不上用null表示。

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


3、右連線

右表全部保留,左表關聯不上的用null表示。

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

4、內連線

兩表關聯,保留兩表中交集的記錄。

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

5、左表獨有

兩表關聯,查詢左表獨有的資料。

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

6、右表獨有

兩表關聯,查詢右表獨有的資料。

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

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;

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;