1. 程式人生 > 實用技巧 >重新認識資料庫的連結查詢

重新認識資料庫的連結查詢

來自:https://blog.csdn.net/lukabruce/article/details/80568796

【注意】: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;

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來達到目的。

  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;

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;