1. 程式人生 > 其它 >sql- inner join、left join、right join

sql- inner join、left join、right join

技術標籤:資料庫problemsmysqlsql

前置條件

建立資料庫,建立測試表,插入測試資料

create database test;
use test

create table testJoin_one(
id int(5),
t_desc varchar(200));

insert into testJoin_one(id,t_desc) values(1,'孫悟空'),(3,'沙悟淨'),(5,'豬八戒');

create table testJoin_two(
id int(5),
t_desc varchar(200));

insert into testJoin_two(id,t_desc) values(1,'魯智深'),(2,'林沖'),(4,'吳用');

create table testJoin_three(
id int(5),
t_desc varchar(200));

insert into testJoin_three(id,t_desc) values(2,'劉備'),(5,'關羽'),(7,'張飛');

測試相關命令

一次查詢(單個join)

  • select * from testJoin_one a inner join testJoin_two b on a.id=b.id;
    在這裡插入圖片描述

  • select * from testJoin_one a left join testJoin_two b on a.id=b.id;
    在這裡插入圖片描述

  • select * from testJoin_one a right join testJoin_two b on a.id=b.id;
    在這裡插入圖片描述

總結

  • inner join 表示join兩邊的表都有比較的值時保留記錄,不滿足則排除。
  • left join 表示 向 join 的左邊看齊,如果右邊沒有對應的記錄,以null填充
  • right join 表示 向 join 的右邊看齊,如果左邊沒有對應的記錄,以null填充

兩次查詢(兩個join)

  • select * from testJoin_one a inner join testJoin_two b on a.id=b.id inner join testJoin_three c on a.id=c.id;
    在這裡插入圖片描述

  • select * from testJoin_one a inner join testJoin_two b on a.id=b.id right join testJoin_three c on a.id=c.id;
    在這裡插入圖片描述

  • select * from testJoin_one a inner join testJoin_two b on a.id=b.id left join testJoin_three c on a.id=c.id;


    在這裡插入圖片描述

  • select * from testJoin_one a right join testJoin_two b on a.id=b.id inner join testJoin_three c on a.id=c.id;
    在這裡插入圖片描述

  • select * from testJoin_one a right join testJoin_two b on a.id=b.id right join testJoin_three c on a.id=c.id;
    在這裡插入圖片描述

  • select * from testJoin_one a right join testJoin_two b on a.id=b.id left join testJoin_three c on a.id=c.id;
    在這裡插入圖片描述

  • select * from testJoin_one a left join testJoin_two b on a.id=b.id inner join testJoin_three c on a.id=c.id;
    在這裡插入圖片描述

  • select * from testJoin_one a left join testJoin_two b on a.id=b.id right join testJoin_three c on a.id=c.id;
    在這裡插入圖片描述

  • select * from testJoin_one a left join testJoin_two b on a.id=b.id left join testJoin_three c on a.id=c.id;
    在這裡插入圖片描述

總結

兩個join 的情況是根據左右順序依次執行,右邊的join 執行的是左邊join執行之後的結果集。
舉個例子
select * from testJoin_one a left join testJoin_two b on a.id=b.id right join testJoin_three c on a.id=c.id;
此處,先執行的是select * from testJoin_one a left join testJoin_two b on a.id=b.id,它的執行結果是
在這裡插入圖片描述
在此基礎上執行right join 操作,此時比對a.id和c.id 可以發現只有5 滿足,故結果是
在這裡插入圖片描述