通俗易懂之MySQL-left join和 right join的用法

通俗易懂之MySQL-left join和 right join的用法

 

這兩個東西容易混淆,今天來說講spa

1、準備工做code

首先建立 2 個表 t1 和 t2, 並插入數據blog

CREATE TABLE `t1` (
  `id1` int(11) NOT NULL AUTO_INCREMENT,
  `num1` int(11) DEFAULT NULL,
  PRIMARY KEY (`id1`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1

insert into t1 values(1,10),(2,20),(3,30),(4,40),(5,50);

table t1.pngit

CREATE TABLE `t2` (
  `id2` int(11) NOT NULL AUTO_INCREMENT,
  `num2` int(11) DEFAULT NULL,
  PRIMARY KEY (`id2`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1

insert into t2 values(1,100),(3,300),(5,500),(7,700),(9,900);

table t2.pngio

2、left jointable

官方解釋,裝逼用的,能夠跳過sed

MySQL implements an A LEFT JOIN B join_condition as follows:select

  • Table B is set to depend on table A and all tables on which A depends.
  • Table A is set to depend on all tables (except B) that are used in the LEFT JOIN condition.
  • If there is a row in A that matches the WHERE clause, but there is no row in B that matches the ON condition, an extra B row is generated with all columns set to NULL.

在終端輸入select * from t1 left join t2 on t1.id1=t2.id2;輸出以下終端

left join.pngim

 

也就是說,表t1左聯接表t2, 左邊t1是老大,右邊t2是跟隨者
表t1全部的記錄都會顯示出來,
而表t2只會顯示出知足join_condition的條件的記錄,即ti.id1=t2.id2,若是存在t1有的記錄而t2沒有,則顯示NULL

3、right join

right join只是恰好反過來而已,右邊的表是老大,左邊的是跟隨者
在終端輸入select * from t1 right join t2 on t1.id1=t2.id2;輸出以下

相關文章
相關標籤/搜索