MySQL让人又爱又恨的多表查询

MySQL让人又爱又恨的多表查询
  1. 前言

在SQL开发当中,多表联查是绝对绕不开的一种技能。同样的查询结果不同的写法其运行效率也是千差万别。

在实际开发当中,我见过(好像还写过~)不少又长又臭的查询SQL,数据量一上来查个十几分钟那是家常便饭。

因此,深入理解SQL的多表查询机制,少写一些慢查询,应该可以少挨点骂。

MySQL让人又爱又恨的多表查询
  1. 等值连接和非等值连接

2.1 等值连接

等价连接是最基本、最简单的一种多表查询,它的值都是满足条件的笛卡尔乘积。

[En]

Equivalent join is the most basic and simplest kind of multi-table query, and its value is all Cartesian products that satisfy the conditions.

在from后面,哪个表写在前面结果中哪个表的值就先出现,如下:

select *
from student,
     family
where student.family_id = family.id;

MySQL让人又爱又恨的多表查询

阿里在最新发布的Java开发手册中强制要求, 只要涉及多个表,必须在列名前加表的别名(或表名)进行限定

MySQL让人又爱又恨的多表查询

2.2 非等值连接

非等值连接是通过a表中的值在b表中的某一个范围来进行的,能够很好的满足预设定好的分段统计需求。

非等值连接有两种写法,使用 between…and…或大于号小于号

-- 第一种写法:使用between...and...

select a.discipline_name, a.score, b.grade_tag
from achievement a,
     achievement_grade b
where a.score between b.lowest_score and b.highest_score;

-- 第二种写法,使用>=或= b.lowest_score
  and a.score

MySQL让人又爱又恨的多表查询
  1. 自连接和非自连接

3.1 自连接

自联接,顾名思义,是指同一个表连接到自己,需要不同的别名来区分该表。例如,对于成绩单,您需要查询所有得分高于中文的数据:

[En]

Self-join, as the name implies, means that the same table is connected to itself, and different aliases are needed to distinguish the table. For example, for a transcript, you need to query all the data with a higher score than “Chinese”:

MySQL让人又爱又恨的多表查询

不使用自连接,需要先通过查询语文的分数,然后再查询大于这个分数的数据。

您可以按照以下步骤进行查询:

[En]

You can follow the steps below to query:

-- 先查询语文的分数
select score from achievement where discipline_name = '语文';

-- 再查询分数比语文分数更高的数据
select * from achievement where score > 76;

使用自连接,则可以在一条sq语句里完成查询:

select a.*
from achievement a,
     achievement b
where b.discipline_name = '语文'
  and a.score > b.score;

MySQL让人又爱又恨的多表查询

3.2 非自连接

除自连接外,所有其他都称为非自连接。

[En]

Except for self-connection, all others are called non-self-connection.

  1. 内连接和外连接

内部连接和外部连接的区别本质上是另一种分类方法,例如,内部连接是等价连接。

[En]

The distinction between inner connection and outer connection is essentially another classification method, for example, inner connection is equivalent connection.

  • INTERNAL JOIN:合并具有相同列的两个或多个表的行。结果集不包含一个表与另一个表不匹配的行
    [En]

    Inner join: merge rows of two or more tables with the same column. * the result set does not contain rows in which one table does not match another table * *

  • 外连接:两个表在连接过程中除了返回满足连接条件的行以外 还返回左(或右)表中不满足条件的 行 ,这种连接称为左(或右) 外连接。没有匹配的行时, 结果表中相应的列为空(NULL)。
  • 左外连接:连接条件中左边的表也称为 主表 ,右边的表称为 从表
  • 右外连接:连接条件中右边的表也称为 主表 ,左边的表称为 从表
  • 全外连接

4.1 测试数据

测试用学生表student和家庭表family数据如下:

MySQL让人又爱又恨的多表查询

MySQL让人又爱又恨的多表查询

4.2 左外连接

-- 查出student中的所有数据,不满足的显示为null
-- 这里student在前面
select a.*
from student a
         left join family b on a.family_id = b.id

MySQL让人又爱又恨的多表查询

4.3 右外连接

-- 查出student中的所有数据,不满足的显示为null
-- 这里student在后面
select a.*
from family b
         right join student a on b.id = a.family_id;

MySQL让人又爱又恨的多表查询

4.4 全外连接

很遗憾,MySQL不支持全外连接。

附录:测试数据SQL脚本

-- auto-generated definition
create table student
(
    id           int auto_increment
        primary key,
    student_id   int                                null comment '学号',
    student_name varchar(40)                        null comment '姓名',
    family_id    int                                null comment '家庭ID',
    create_time  datetime default CURRENT_TIMESTAMP null comment '创建时间'
)
    comment '学生表';

create table family
(
    id             int auto_increment
        primary key,
    family_name    varchar(40)                        null comment '家庭名称',
    family_address varchar(40)                        null comment '家庭地址',
    create_time    datetime default CURRENT_TIMESTAMP null comment '创建时间'
)
    comment '家庭表';

create table achievement
(
    id              int auto_increment
        primary key,
    score           int         null comment '分数',
    discipline_name varchar(40) null comment '学科名称',
    student_id      int         null comment '学号'
)
    comment '成绩表';

create table achievement_grade
(
    id            int auto_increment
        primary key,
    grade_tag     varchar(10)                        null comment '档次',
    lowest_score  int                                null comment '最低分',
    highest_score int                                null comment '最高分',
    create_time   datetime default CURRENT_TIMESTAMP null comment '创建时间'
)
    comment '分数档次表';

INSERT INTO achievement_grade (id, grade_tag, lowest_score, highest_score, create_time) VALUES (1, '不及格', 0, 60, '2022-03-02 11:44:01');
INSERT INTO achievement_grade (id, grade_tag, lowest_score, highest_score, create_time) VALUES (2, '良好', 60, 80, '2022-03-02 11:44:01');
INSERT INTO achievement_grade (id, grade_tag, lowest_score, highest_score, create_time) VALUES (3, '优秀', 80, 100, '2022-03-02 11:44:01');

INSERT INTO student (id, student_id, student_name, family_id, create_time) VALUES (1, 1, '张三', 1, '2022-03-02 09:55:01');
INSERT INTO student (id, student_id, student_name, family_id, create_time) VALUES (2, 2, '李四', 2, '2022-03-02 09:55:01');
INSERT INTO student (id, student_id, student_name, family_id, create_time) VALUES (3, 3, '王五', 3, '2022-03-02 09:55:01');
INSERT INTO student (id, student_id, student_name, family_id, create_time) VALUES (4, 4, '高飞', null, '2022-03-02 19:45:14');

INSERT INTO family (id, family_name, family_address, create_time) VALUES (1, '张三家', '北京', '2022-03-02 09:54:13');
INSERT INTO family (id, family_name, family_address, create_time) VALUES (2, '李四家', '上海', '2022-03-02 09:54:13');
INSERT INTO family (id, family_name, family_address, create_time) VALUES (3, '王五家', '西伯利亚', '2022-03-02 09:54:13');

INSERT INTO achievement (id, score, discipline_name, student_id) VALUES (1, 76, '语文', 1);
INSERT INTO achievement (id, score, discipline_name, student_id) VALUES (2, 80, '数学', 1);
INSERT INTO achievement (id, score, discipline_name, student_id) VALUES (3, 65, '英语', 1);
INSERT INTO achievement (id, score, discipline_name, student_id) VALUES (4, 98, '地理', 1);
INSERT INTO achievement (id, score, discipline_name, student_id) VALUES (5, 77, '历史', 1);
INSERT INTO achievement (id, score, discipline_name, student_id) VALUES (6, 69, '生物', 1);

微信搜索:『深海云帆』关注我的众号
或者加我微信:hqzmss,拉你入技术交流群

Original: https://www.cnblogs.com/hqzmss/p/15958203.html
Author: 深海云帆
Title: MySQL让人又爱又恨的多表查询

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/507788/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • 学习笔记——Django项目中的请求与响应

    2022-10-01 ALLOWED_HOSTS “ALLOWED_HOSTS”的含义: 它是指允许放在”ALLOWED_HOSTS&#8221…

    数据库 2023年6月14日
    092
  • md5解密异常

    javax.crypto.BadPaddingException: Given final block not properly paddedat com.sun.crypto.p…

    数据库 2023年6月11日
    097
  • Vim配置文件-详解(.vimrc)

    Vim配置文件的作用 Vim启动时,会根据配置文件(.vimrc)来设置 Vim,因此我们可以通过此文件来定制适合自己的 Vim 所有系统用户在启动Vim时,都会加载这个配置文件。…

    数据库 2023年6月14日
    078
  • Java 考试系统项目源码 springboot mybaits vue.js 支持手机端考试

    新增功能:培训学习模块, PDF电子课程、视频课程、直播课程(自己搭建直播流服务器) 人脸识别(考试时验证,有开关)、补考开关 组建试卷:创建试卷,题目、类型、总分、及格分数、时长…

    数据库 2023年6月6日
    081
  • 11、ON DUPLICATE KEY UPDATE实现插入更新操作

    一、插入与更新操作: MySQL中,采用ON DUPLICATE KEY UPDATE语句对不存在的数据进行INSERT插入操作,对已存在的数据进行UPDATE更新操作; 总结: …

    数据库 2023年6月6日
    060
  • 如何成为一名开发人员——第 1 部分:编码技巧

    1 学习一门语言 程序员编写计算机代码,所以你必须学会说这种语言。 但是, 你首先学习哪种编程语言并不重要!这完全取决于你对什么感兴趣。例如… 如果你想进入 Web 开…

    数据库 2023年6月14日
    0100
  • 每个开发人员都应该关注的7个优秀的GitHub仓库

    1. FreeCodeCamp 2. Developer Roadmap 3. Awesome 4. Build Your Own X 5. Git Ignore 6. Syste…

    数据库 2023年6月11日
    0100
  • 数据库设计的十个最佳实践

    数据库是应用及计算机的核心元素,负责存储运行软件应用所需的一切重要数据。为了保障应用正常运行,总有一个甚至多个数据库在默默运作。我们可以把数据库视为信息仓库,以结构化的方式存储了大…

    数据库 2023年5月24日
    0101
  • PHP array_reduce()

    array_reduce array_reduce() 将回调函数 callback 迭代地作用到 array 数组中的每一个单元中,从而将数组简化为单一的值。 示例一: 示例二:…

    数据库 2023年6月14日
    093
  • IDEA 常用插件

    插件使用参考:Idea插件系列 插件名称 说明 IDE Eval Reset 破解软件 Alibaba Java Coding Guidelines 阿里巴巴开发规范 tabnin…

    数据库 2023年6月6日
    087
  • Git的常见命令

    Git 一、git环境安装 1.初始化本地仓库: git init 2.将本地仓库跟远程仓库建立连接:git remote add name path ​ git clone pa…

    数据库 2023年6月16日
    082
  • redis实现分布式锁导致的问题

    解决缓存击穿的问题(加锁) 1.虽然spring组件都是单例的,但是到了多个机器部署服务的情况下这种单机锁就不可行了 使用分布式锁 1.有可能占用锁的那个线程因为宕机没有删除锁,导…

    数据库 2023年6月16日
    086
  • Mysql索引底层数据结构与算法

    一.索引概述是什么:索引是帮助MySQL高效获取数据的排好序的数据结构,索引叫”键”,优化好一个索引,可以提高数倍的性能, 类似于字典的音序表为什么要键索引…

    数据库 2023年6月11日
    0112
  • Linux指令_入门基础

    2.pwd指令 : 用法:#pwd (print working directory ,打印当前工作目录) 3.cd指令 : 命令:# cd (change directory,改…

    数据库 2023年6月11日
    0103
  • MySQL学习(4)—MySQL索引

    ps:没有特殊说明,此随笔中默认采用innoDB存储引擎中的索引,且索引都是指B+树(多路平衡搜索树)结构组织的索引。其中聚集索引、复合索引、前缀索引、唯一索引默认都是使用B+树,…

    数据库 2023年6月14日
    078
  • 在ESXI6.7中安装OpenWrt

    在ESXI6.7中安装OpenWrt 21.02.2 一、前置准备 安装好的esxi6.7 下载openwrt镜像,如:openwrt-21.02.2-x86-64-generic…

    数据库 2023年6月9日
    0114
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球