当前位置:网站首页>【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右边为主表)
以上就是多表联查的几种方式,希望对看到这里的你有所帮助。与君共勉。
边栏推荐
- 【过一下16】回顾一下七月
- Calling Matlab configuration in pycharm: No module named 'matlab.engine'; 'matlab' is not a package
- Dashboard Display | DataEase Look at China: Data Presents China's Capital Market
- day8字典作业
- OFDM 十六讲 5 -Discrete Convolution, ISI and ICI on DMT/OFDM Systems
- A blog clears the Redis technology stack
- 2022杭电多校第一场01
- DOM及其应用
- npm搭建本地服务器,直接运行build后的目录
- 【过一下14】自习室的一天
猜你喜欢

A blog clears the Redis technology stack

The software design experiment four bridge model experiment

Pandas(五)—— 分类数据、读取数据库

2022 Hangzhou Electric Multi-School 1st Session 01

Lecture 4 Backpropagation Essays

【练一下1】糖尿病遗传风险检测挑战赛 【讯飞开放平台】

Using pip to install third-party libraries in Pycharm fails to install: "Non-zero exit code (2)" solution

Lecture 2 Linear Model Linear Model

软件设计 实验四 桥接模式实验

DOM及其应用
随机推荐
ESP32 485 Illuminance
HQL语句执行过程
HQL statement execution process
【过一下9】卷积
day11-函数作业
数据库 单表查询
What field type of MySQL database table has the largest storage length?
学习总结week2_2
物理层的接口有哪几个方面的特性?各包含些什么内容?
server disk array
"Recursion" recursion concept and typical examples
机器学习(二) —— 机器学习基础
【过一下11】随机森林和特征工程
[Go through 7] Notes from the first section of the fully connected neural network video
Map、WeakMap
学习总结week2_3
鼠标放上去变成销售效果
【过一下15】学习 lstm的一周
Qt produces 18 frames of Cupid to express his love, is it your Cupid!!!
怎么更改el-table-column的边框线