通俗易懂之MySQL-left join和 right join的用法
这两个东西容易混淆,今天来讲讲
一、准备工作
首先创建 2 个表 t1 和 t2, 并插入数据
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=latin1insert into t1 values(1,10),(2,20),(3,30),(4,40),(5,50);
table t1.png
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=latin1insert into t2 values(1,100),(3,300),(5,500),(7,700),(9,900);
table t2.png
二、left join
官方解释,装逼用的,可以跳过
MySQL implements an A LEFT JOIN B join_condition as follows:
- 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.png
也就是说,表t1左联接表t2, 左边t1是老大,右边t2是跟随者
表t1所有的记录都会显示出来, 而表t2只会显示出满足join_condition的条件的记录,即ti.id1=t2.id2,如果存在t1有的记录而t2没有,则显示NULL三、right join
right join只是刚好反过来而已,右边的表是老大,左边的是跟随者
在终端输入select * from t1 right join t2 on t1.id1=t2.id2;
输出如下