MySQL表关联的几种常用方式

jerryliuxin 2021-12-03 原文

MySQL表关联的几种常用方式

工作中我们经常会使用表与表关联来查询数据,如果对join 不熟悉,可能会得到我们不想要的节过,这里就来介绍下join的几种常用方法:
建表及插入数据,
CREATE TABLE school (
sch_id int(11) NOT NULL AUTO_INCREMENT,
sch_name varchar(50) NOT NULL,
sch_addr varchar(100) DEFAULT NULL,
PRIMARY KEY (sch_id)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

CREATE TABLE student (
st_id int(11) NOT NULL AUTO_INCREMENT,
st_name varchar(20) NOT NULL,
age smallint(6) DEFAULT NULL,
hight int(5) DEFAULT NULL,
sch_id int(11) DEFAULT NULL,
PRIMARY KEY (st_id),
KEY sch_id (sch_id)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 ;

INSERT INTO school VALUES (1,\’南开大学\’,\’南开\’),(2,\’中央财经大学\’,\’北京\’),(3,\’香港理工大学\’,\’香港\’),(4,\’西安交通大学\’,\’西安\’),(5,\’悉尼大学\’,\’悉尼\’),(6,\’曼彻斯特大学\’,\’曼彻斯特\’),(8,\’延安抗日军政大学\’,\’延安\’);

INSERT INTO student VALUES (1,\’王晓阳\’,26,168,6),(2,\’王楠\’,28,162,2),(3,\’杨振宇\’,30,178,1),(4,\’苗昕\’,28,162,3),(5,\’张诗雨\’,27,171,5),(8,\’李倩\’,28,162,4),(9,\’蒋结石\’,26,178,7);

1.左关联:以左表为中心,查出左表的全部数据,关联字段值不相等则右表查出的数据显示为空;
select * from school a left join student b on a.sch_id=b.sch_id;

MySQL表关联的几种常用方式

MySQL表关联的几种常用方式

2.右关联:以右表为中心,查出右表的全部数据,关联字段值不相等则左表查出的数据显示为空;
select * from school a right join student b on a.sch_id=b.sch_id;

MySQL表关联的几种常用方式

MySQL表关联的几种常用方式

3.内关联:查出两表关联字段等值的数据
select * from school a inner join student b on a.sch_id=b.sch_id;
MySQL表关联的几种常用方式

MySQL表关联的几种常用方式

4.查出只属于左表的数据
select * from school a left join student b on a.sch_id=b.sch_id where b.st_id is null;
MySQL表关联的几种常用方式

MySQL表关联的几种常用方式

5.查出只属于右表的数据
select * from school a right join student b on a.sch_id=b.sch_id where a.sch_id is null;
MySQL表关联的几种常用方式

MySQL表关联的几种常用方式

6.查出全部数据
select * from school a left join student b on a.sch_id=b.sch_id union select * from school a right join student b on a.sch_id=b.sch_id;
MySQL表关联的几种常用方式

MySQL表关联的几种常用方式

7.查出左表和右表关联不相等的数据
select * from school a left join student b on a.sch_id=b.sch_id where b.st_id is null union select * from school a right join student b on a.sch_id=b.sch_id where a.sch_id is null;

MySQL表关联的几种常用方式

MySQL表关联的几种常用方式

版权声明:本文为jerryliuxin原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/jerryliuxin/p/10975032.html

MySQL表关联的几种常用方式的更多相关文章

随机推荐

  1. 设计模式之状态模式实战

    本文原文链接地址:http://nullpointer.pw/design-patterns-state.ht […]...

  2. 快速幂和矩阵快速幂

    快速幂 如计算 a^b^ ,代码如下: 快速幂代码 int multi(int a,int b) { int […]...

  3. Git & Github

      为什么要用版本控制? 假设你在的公司要上线一个新功能,你们开发团队为实现这个新功能,写了大约5000行代码 […]...

  4. Java方法-数组

    【Java数组】 1. 用sort()方法对Java数组进行排序,及如何使用 binarySearch() 方 […]...

  5. JVM学习记录-对象已死吗

    前言 先来回顾一下,在jvm运行时数据区,分为两部分,一个部分是线程共享区,主要包括堆和方法区,另一部是线程私 […]...

  6. Oracle触发器的语法详解

    触发器是一种特殊的存储过程,下面是触发器的详细说明:   ORACLE 触发器   ORACLE产生数据库触发 […]...

  7. crontab不能执行sudo:抱歉,您必须拥有一个终端来执行 sudo

    最近做一个可行shell调度的需求,要求用户输入shell,然后后台定时调度运行。实现大致为:保存用户的输入, […]...

  8. 了解 HTTPS,读这篇文章就够了

    今天接到个活儿,让我科普 HTTPS 。讲 HTTP 我都“方”,想要通俗易懂的说完 HTTPS, 我有点“圆 […]...

展开目录

目录导航