博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
通俗易懂之MySQL-left join和 right join的用法
阅读量:6887 次
发布时间:2019-06-27

本文共 1325 字,大约阅读时间需要 4 分钟。

hot3.png

通俗易懂之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);

464

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);

420

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

700

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

700

转载于:https://my.oschina.net/fadoudou/blog/1615765

你可能感兴趣的文章
我的友情链接
查看>>
性能优化之Java(Android)代码优化
查看>>
nagios自定义插件
查看>>
关于字符串的拼接
查看>>
nginx 反向代理 取得真实IP和域名
查看>>
最实用的Spring Data JPA功能
查看>>
我的软件之路
查看>>
如何用消息系统避免分布式事务?
查看>>
【python】编程语言入门经典100例--39
查看>>
Solr5.5版本使用tika索引文件夹下所有文件
查看>>
SNMP 客户端配置
查看>>
windows server 2016 系统管理 (五)
查看>>
linux+nginx+python+django环境配置
查看>>
文件上传时几个Content-type
查看>>
我的友情链接
查看>>
Exchange Server 2013 集成Office Web App
查看>>
字节转换工具,在线字节转换工具
查看>>
实验心得
查看>>
Oracle 11g 数据库启动和关闭
查看>>
mysql 生成行号
查看>>