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

通俗易懂之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=latin1

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

624ea4d7e53cbaae792d498790cef860.png

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=latin1

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

9ea7db475b01ecfd1061fe9eaa9d8ed6.png

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;输出如下

e3f4b65c9d2a754760cf86a8b6d331be.png

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;输出如下

007139bf9f09f2665d7f7fbca081bfb4.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值