当前位置:网站首页>【MySQL】数据库多表链接的查询方式
【MySQL】数据库多表链接的查询方式
2022-08-05 05:13:00 【来一杯奶喵】
数据库的多表联查可以通过连接运算实现,即将多张表通过主外键关系关联在一起进行查询。
多表联查的方式主要分为两大类:非等值联查和等值联查。
首先先建立了两张表:student表、sc表。基于这两张表演示多表联查。
create table Student(
Sid int primary key auto_increment,
Sname varchar(10),
birthday datetime,
Ssex varchar(10),
classid int
);
create table SC(
Sid int,
Cid int,
score decimal(18,1),
foreign key(Sid) references Student(Sid),
foreign key(Cid) references Course(Cid)
);
非等值联查:
select * from student,sc
这种查询会产生笛卡尔积:也就是student表内所有数据以及sc表内所有数据的乘积。这种情况是由于没有有效的连接条件产生的,并不适用于表内存在大量数据的情况。为避免笛卡尔积的产生就需要用到等值联查。
等值联查:
select * from studend,sc where student.sid = sc.sid这种使用where子句的等值查询方式只适用于表内数据量小的情况,且只能挑选一次
等值查询有内联查询和外联查询。
我们先来看看内联查询(数据量大时使用,虚拟表按照数据量最大的表创建):
语法:select * from 表1 inner join 表2 on 条件
select * from student inner join sc on student.sid = sc.sid这条内联查询语句得到的数据是筛选两个表内相同sid的记录,至少有一行记录匹配,就能返回结果,如下图所示:

外联查询:左外联、右外联
左外联查询:显示主表全部信息,join左边为主查表
语法:select * from 表1 left join 表2 on 条件
select * from student left join sc on student.sid = sc.sid以student表为主表查询记录,所以没有成绩的学生记录也在查询结果中,如下图所示:

右外联查询: 显示主表全部信息,join右边为主查表
语法:select * from 表1 right join 表2 on 条件
select * from student right join sc on student.sid = sc.sid以sc表为主表查询记录,从sc中返回所有的记录,即便在student中没有匹配的行。
如下图所示:
总结:
多表联查的方式:
1.非等值联查,产生笛卡尔积,不适合数据量大时使用
2.等值查询,【单独where子句查询,内联查询,外联查询(左外联,右外联)】
①单纯使用where子句,同样不适合大量数据时使用
②内联查询 inner join
③左外联查询 left join (join左边为主表)
④右外联查询 right join (join右边为主表)
以上就是多表联查的几种方式,希望对看到这里的你有所帮助。与君共勉。
边栏推荐
猜你喜欢
![[Go through 3] Convolution & Image Noise & Edge & Texture](/img/7b/2214020cadf06d9211fd40fb5f1b63.png)
[Go through 3] Convolution & Image Noise & Edge & Texture

Reverse theory knowledge 4

第三讲 Gradient Tutorial梯度下降与随机梯度下降
![[Go through 7] Notes from the first section of the fully connected neural network video](/img/e2/1107171b52fe9dcbf454f7edcdff77.png)
[Go through 7] Notes from the first section of the fully connected neural network video

机器学习(一) —— 机器学习基础

第四讲 反向传播随笔

【After a while 6】Machine vision video 【After a while 2 was squeezed out】

【Transfer】What is etcd

怎么更改el-table-column的边框线

A blog clears the Redis technology stack
随机推荐
el-table鼠标移入表格改变显示背景色
JSX基础
number_gets the specified number of decimals
Pycharm中使用pip安装第三方库安装失败:“Non-zero exit code (2)“的解决方法
Flex layout frog game clearance strategy
【练一下1】糖尿病遗传风险检测挑战赛 【讯飞开放平台】
Pandas(五)—— 分类数据、读取数据库
【过一下7】全连接神经网络视频第一节的笔记
redis 缓存清除策略
多线程查询结果,添加List集合
The underlying mechanism of the class
【技能】长期更新
Using pip to install third-party libraries in Pycharm fails to install: "Non-zero exit code (2)" solution
[Go through 3] Convolution & Image Noise & Edge & Texture
day6-列表作业
Lecture 5 Using pytorch to implement linear regression
phone call function
02.01-----The role of parameter reference "&"
A blog clears the Redis technology stack
day9-字符串作业