通俗易懂之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;输出以下

相关文章
相关标签/搜索