首页 > 数据库 >跟着黑马学MySQL基础篇笔记(4)-多表查询

跟着黑马学MySQL基础篇笔记(4)-多表查询

时间:2024-09-23 17:49:28浏览次数:3  
标签:comment 多表 name 查询 MySQL null id 黑马

37.多表查询-多表关系介绍

多表关系

  • 概述

    项目开发中,在进行数据库表结构设计时,会根据业务需求及业务模块之间的关系,分析并设计表结构,由于业务之间相互关联,所以各个表结构之间也存在着各种联系,基本上分为三种:

    • 一对多(多对一)
    • 多对多
    • 一对一
  • 一对多(多对一)

    • 案例:部门与员工的关系
    • 关系:一个部门对应多个员工,一个员工对应一个部门
    • 实现:在多的一方建立外键,指向一的一方的主键
  • 多对多

    • 案例:学生与课程的关系

    • 一个学生可以选修多门课程,一门课程也可以供多个学生选择

    • 实现:建立第三张中间表,中间表至少包含两个外键,分别关联两方主键

    • -- 多对多
      create table student(
          id int auto_increment primary key comment '主键ID',
          name varchar(10) comment '课程名称',
          no varchar(10) comment '学号'
      ) comment '学生表';
      
      create table course(
          id int auto_increment primary key comment '主键ID',
          name varchar(10) comment '课程名称'
      ) comment '课程表';
      
      insert into student (name, no) values ('黛绮丝', '2000100101'),
                                            ('谢逊', '2000100102'),
                                            ('殷天正', '2000100103'),
                                            ('韦一笑', '2000100104');
      
      insert into course (name) values ('Java'), ('PHP'), ('MySQL'), ('Hadoop');
      
      -- 建立多对多中间表
      create table student_course(
          id int auto_increment primary key comment '主键',
          studentid int not null comment '学生ID',
          courseid int not null comment '课程ID',
          constraint fk_student foreign key (studentid) references student(id),
          constraint fk_course foreign key(courseid) references course(id)
      ) comment '学生课程中间表';
      
      insert into student_course values (null, 1, 1),
                                        (null, 1, 2),
                                        (null, 1, 3),
                                        (null, 2, 2),
                                        (null, 2, 3),
                                        (null, 3, 4);
      
  • 一对一

    • 案例:用户与用户详情的关系

    • 关系:一对一关系,用于单表拆分,将一张表的基础字段放在一张表中,其他详情字段放在另一张表中,以提升操作效率

    • 实现:**在任意一方加入外键,关联另外一方的主键,并且设置外键为唯一的(UNIQUE

    • -- 一对一
      create table tb_user(
          id int primary key auto_increment comment '编号',
          name varchar(50) unique comment '姓名',
          age int check (age >= 0 and age <= 120) comment '年龄',
          gender char(1) check (gender in ('男', '女')) comment '性别',
          phone char(11) unique comment '电话号码'
      ) comment '用户基本信息表';
      
      create table tb_user_edu(
          id int auto_increment primary key comment '编号',
          degree varchar(4) comment '学历',
          major varchar(50) comment '专业',
          primary_school varchar(50) comment '小学',
          middle_school varchar(50) comment '中学',
          university varchar(50) comment '大学',
          userid int unique comment '用户id',
          constraint fk_user_id foreign key (userid) references tb_user(id)
      ) comment '用户教育信息表';
      
      insert into tb_user (id, name, age, gender, phone) values
                                  (null, '黄渤', 45, '男', '18800001111'),
                                  (null, '冰冰', 35, '女', '18800002222'),
                                  (null, '码云', 55, '男', '18800008888'),
                                  (null, '李彦宏', 50, '男', '18800009999');
      
      insert into tb_user_edu (degree, major, primary_school, middle_school, university, userid)
      values ('本科', '舞蹈', '静安区第一小学', '静安区第一中学', '北京舞蹈学院', 1),
             ('硕士', '表演', '朝阳区第一小学', '朝阳区第一中学', '北京电影学院', 2),
             ('本科', '英语', '杭州市第一小学', '杭州市第一中学', '杭州师范大学', 3),
             ('本科', '应用数学', '阳泉第一小学', '阳泉区第一中学', '清华大学', 4);
      

38.多表查询-概述

  • 概述:指从多张表中查询数据
  • 笛卡尔积:笛卡尔乘积是指在数学中,两个集合A集合和B集合的所有组合情况。(在多表查询时,需要消除无效的笛卡尔积
  • 多表查询分类
    • 连接查询
      • 内连接:相当于查询A、B交集部分数据
      • 外连接:
        • 左外连接:查询左表所有数据,以及两张表交集部分数据
        • 右外连接:查询右表所有数据,以及两张表交集部分数据
      • 自连接:当前表与自身的连接查询,自连接必须使用通过表别名
    • 子查询

39. 多表查询-内连接

内连接查询语法:

  • 隐式内连接

    SELECT 字段列表 FROM 表1, 表2 WHERE 条件...;
    
  • 显式内连接

    SELECT 字段列表 FROM 表1 [INNER] JOIN 表2 ON 连接条件...; 
    
  • 内连接查询的是两张表交集的部分

40.多表查询-外连接

  • 左外连接

    SELECT 字段列表 FROM 表1 LEFT [OUTER] JOIN 表2 ON 条件...;
    

    相当于查询表1(左表)的所有数据包含表1和表2交集部分的数据

  • 右外连接

    SELECT 字段列表 FROM 表1 RIGHT [OUTER] JOIN 表2 ON 条件...;
    

    相当于查询表2(右表)的所有数据包含表1和表2交集部分的数据

41.多表查询-自连接

SELECT 字段列表 FROM 表A 别名A JOIN 表A 别名B ON 条件...;

自连接查询,可以是内连接查询也可以是外连接查询

42.多表查询-联合查询union

对于union查询就是把多次查询的结果合并起来,形成一个新的查询结果集。

SELECT 字段列表 FROM 表A...
UNION [ALL]
SELECT 字段列表 FROM 表B...;

all 不会去重,没有 all 会去重

对于联合查询的多张表的列数必须保持一致,字段类型也需要保持一致

43.多表查询-子查询介绍

概念:SQL语句中嵌套SELECT语句,称为嵌套查询,又称子查询

SELECT * FROM t1 WHERE column1 = (SELECT column1 from t2);

子查询外部的语句可以是INSERT\UPDATE\DELETE\SELECT的任何一个

根据子查询结果不同,分为:

  • 标量子查询(子查询结果为单个值)
  • 列子查询(子查询结果为一列)
  • 行子查询(子查询结果为一行)
  • 表子查询(子查询结果为多行多列)

根据子查询位置,分为:WHERE之后、FROM之后、SELECT之后

44.多表查询-标量子查询

  • 标量子查询

    子查询返回的结果是单个值(数字、字符串、日期等),最简单的形式,这种子查询称为标量子查询

    常用的操作符:= <> > >= < <=

45.多表查询-列子查询

  • 列子查询

    子查询返回的结果是一列(可以是多行),这种子查询称为列子查询

    常用操作符:IN \ NOT IN \ ANY \ SOME \ ALL

操作符描述
IN在指定的集合范围之内,多选一
NOT IN不在指定的集合范围之内
ANY子查询返回列表中,有任意一个满足即可
SOMEANY 等同,使用 SOME 的地方都可以使用 ANY
ALL子查询返回列表的所有值都必须满足

46.多表查询-行子查询

  • 行子查询

    子查询返回的结果是一行(可以是多列),这种子查询称为行子查询

    常用操作符:=、<>、INNOT IN

47.多表查询-表子查询

  • 表子查询

    子查询返回的结果是多行多列,这种子查询称为表子查询

    常用操作符:IN

48.多表查询-练习1

1.创建表和原始数据

dept

create table dept(
    id int primary key auto_increment comment '部门编号',
    name varchar(10) comment '部门名称'
);

insert into dept (name) values ('研发部'), ('市场部'), ('财务部'),
                               ('销售部'), ('总经办'), ('人事部');

emp

create table emp(
    id int primary key auto_increment comment '员工id',
    name varchar(10) comment '员工姓名',
    age int comment '员工年龄',
    job varchar(10) comment '员工职位',
    salary int comment '员工薪资',
    entrydate date comment '员工入职日期',
    managerid int comment '员工的上司编号',
    dept_id int comment '员工所在的部门编号',
    constraint fk_dept foreign key (dept_id) references dept(id)
) comment '员工表';

insert into emp (id, name, age, job, salary, entrydate, managerid, dept_id) values
                (null, '金庸', 66, '总裁', 20000, '2000-01-01', null, 5),
                (null, '张无忌', 20, '项目经理', 12500, '2005-12-05', 1, 1),
                (null, '杨逍', 33, '开发', 8400, '2000-11-03', 2, 1),
                (null, '韦一笑', 48, '开发', 11000, '2002-02-05', 2, 1),
                (null, '常遇春', 43, '开发', 10500, '2004-09-07', 3, 1),
                (null, '小昭', 19, '程序员鼓励师', 6600, '2004-10-12', 2, 1),
                (null, '灭绝', 60, '财务总监', 8500, '2002-09-12', 1, 3),
                (null, '周芷若', 19, '会计', 4800, '2006-06-02', 7, 3),
                (null, '丁敏君', 23, '出纳', 5250, '2009-05-13', 7, 3),
                (null, '赵敏', 20, '市场部总监', 12500, '2004-10-12', 1, 2),
                (null, '鹿杖客', 56, '职员', 3750, '2006-10-03', 10, 2),
                (null, '鹤笔翁', 19, '职员', 3750, '2007-05-09', 10, 2),
                (null, '方东白', 19, '职员', 5500, '2009-02-12', 10, 2),
                (null, '张三丰', 88, '销售总监', 14000, '2004-10-12', 1, 4),
                (null, '俞莲舟', 38, '销售', 4600, '2004-10-12', 14, 4),
                (null, '宋远桥', 40, '销售', 4600, '2004-10-12', 14, 4),
                (null, '陈友谅', 42, null, 2000, '2011-10-12', 1, null);

salgrade

create table salgrade(
    grade int comment '薪资等级',
    losal int comment '最低薪',
    hisal int comment '最高薪'
) comment '薪资等级表';

insert into salgrade (grade, losal, hisal) values (1, 0, 3000),
                                                  (2, 3001, 5000),
                                                  (3, 5001, 8000),
                                                  (4, 8001, 10000),
                                                  (5, 10001, 15000),
                                                  (6, 15001, 20000),
                                                  (7, 20001, 25000),
                                                  (8, 25001, 30000);

2.练习

  1. 查询员工的姓名、年龄、职位、部门信息(隐式内连接)

    select e.name, e.age, e.job, d.name from emp e, dept d where e.dept_id=d.id;
    
  2. 查询年龄小于30岁的员工的姓名、年龄、职位、部门信息(显式内连接)

    select e.name, e.age, e.job, d.name from emp e inner join dept d on e.dept_id=d.id where e.age < 30;
    
  3. 查询拥有员工的部门ID、部门名称

    select distinct d.id, d.name from dept d inner join emp e where d.id = e.dept_id;
    
  4. 查询所有年龄大于40岁的员工,及其归属的部门名称;如果员工没有分配部门,也需要显示出来

    select e.*, d.name from emp e left outer join dept d on e.dept_id = d.id where e.age > 40;
    
  5. 查询所有员工的工资等级

    select e.name, e.salary, s.grade from emp e inner join salgrade s on e.salary>=s.losal and e.salary<=s.hisal;
    select e.name, e.salary, s.grade from emp e inner join salgrade s on e.salary between s.losal and s.hisal;
    

49.多表查询-练习2

  1. 查询“研发部”所有员工的信息及工资等级

    select e.*, s.grade
    from emp e
             inner join salgrade s on e.salary between s.losal and s.hisal
    where e.dept_id = (select d.id from dept d where name = '研发部');
    
  2. 查询“研发部”员工的平均工资

    select avg(e.salary) from emp e, dept d where e.dept_id=d.id and d.name='研发部';
    
  3. 查询工资比“灭绝”高的员工的信息

    select * from emp e where e.salary > (select e.salary from emp e where e.name='灭绝');
    
  4. 查询比平均薪资高的员工信息

    select * from emp e where e.salary > (select avg(e.salary) from emp e);
    
  5. 查询低于本部门平均工资的员工

    select * from emp e1 where e1.salary < (select avg(e2.salary) from emp e2 where e2.dept_id=e1.dept_id);
    
  6. 查询所有部门信息,并统计部门的员工人数

    select d.id, d.name, (select count(*) from emp e where e.dept_id = d.id) '人数' from dept d;
    
  7. 查询所有学生的选课情况,展示出学生的名称,学号,课程信息

    • 建表和初始数据

      -- 多对多
      create table student(
          id int auto_increment primary key comment '主键ID',
          name varchar(10) comment '课程名称',
          no varchar(10) comment '学号'
      ) comment '学生表';
      
      create table course(
          id int auto_increment primary key comment '主键ID',
          name varchar(10) comment '课程名称'
      ) comment '课程表';
      
      insert into student (name, no) values ('黛绮丝', '2000100101'),
                                            ('谢逊', '2000100102'),
                                            ('殷天正', '2000100103'),
                                            ('韦一笑', '2000100104');
      
      insert into course (name) values ('Java'), ('PHP'), ('MySQL'), ('Hadoop');
      
      -- 建立多对多中间表
      create table student_course(
          id int auto_increment primary key comment '主键',
          studentid int not null comment '学生ID',
          courseid int not null comment '课程ID',
          constraint fk_student foreign key (studentid) references student(id),
          constraint fk_course foreign key(courseid) references course(id)
      ) comment '学生课程中间表';
      
      insert into student_course values (null, 1, 1),
                                        (null, 1, 2),
                                        (null, 1, 3),
                                        (null, 2, 2),
                                        (null, 2, 3),
                                        (null, 3, 4);
      
    • 查询所有学生的选课情况,展示出学生的名称,学号,课程信息

      select student.name, student.no, course.name from student, student_course, course where student.id=student_course.studentid and student_course.courseid=course.id;
      

50.多表查询-小结

  1. 多表关系

    一对多:在多的一方设置外键,关联一的一方的主键

    多对多:建立中间表,中间表包含两个外键,关联两张表的主键

    一对一:用于表结构的拆分,在其中任何一方设置外键(UNIQUE),关联另一方的主键

  2. 多表查询

    • 内连接

      • 隐式查询

        SELECT ... FROM 表A, 表B WHERE 条件...
        
      • 显式查询

        SELECT ... FROM 表A INNER JOIN 表B ON 条件...
        
    • 外连接

      • 左外连接

        SELECT ... FROM 表A LEFT OUTER JOIN 表B ON 条件...
        
      • 右外连接

        SELECT ... FROM 表A RIGHT OUTER JOIN 表B ON 条件...
        
    • 自连接

      SELECT ... FROM 表A 别名A, 表A 别名B WHERE 条件...
      
    • 子查询

      标量子查询、列子查询、行子查询、表子查询

标签:comment,多表,name,查询,MySQL,null,id,黑马
From: https://blog.csdn.net/m0_72851153/article/details/142459185

相关文章

  • MySQL 左右连接
    在MySQL中,左连接(LEFTJOIN)和右连接(RIGHTJOIN)都是用于在多个表之间进行关联查询的操作。一、左连接(LEFTJOIN)作用:以左表为基础,返回左表中的所有记录以及与右表中匹配的记录。如果右表中没有匹配的记录,则相应的列将填充为NULL。语法结构:SELECTcolumn_name(s)F......
  • 主从数据库同步配置详解(MySQL/MariaDB)
    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档文章目录前言一、环境准备与安装配置本地部署MySQLUbuntu系统:CentOS系统:MariaDBUbuntu系统:CentOS系统:容器部署MySQLMariaDB二、配置主从库的同步设置四、测试与维护总结前言在数据库管理中,......
  • 【字节跳动面试100题精讲】MySQL 索引文件写入磁盘的完整过程
    欢迎您的阅读,接下来我将为您一步步分析:MySQL索引文件写入磁盘的完整过程。让我们通过多个角度来深入探讨这个问题。MySQL索引文件写入磁盘的完整过程关键词:MySQL、索引、B+树、缓冲池、脏页、检查点、双写缓冲、文件系统缓存、磁盘I/O文章目录MySQL索引文件写入磁......
  • mysql学习笔记1
    安装1.更新sudoaptupdate2.安装$sudoaptinstallmysql-server3.查看运行状况$sudosystemctlstatusmysql.service●mysql.service-MySQLCommunityServerLoaded:loaded(/lib/systemd/system/mysql.service;enabled;vendorpreset:>Active:......
  • MySQL索引
    一.索引是什么MySQL索引是一种数据结构,用于加快数据库查询的速度和性能。大家可以自己试一下有索引和没索引的区别,两者的速度都不是在一个量级上。索引是极大的加快查询数据库的速度。当然,索引这么快也是有代价的,创建索引后会生成索引树,它是占磁盘空间的。磁盘IO是很耗时间......
  • 【PLW003】设备器材云端管理平台v1.0(SpringBoot+Mybatis+NodeJS+MySQL前后端分离)
    设备器材云端管理平台是一种专为各种设备(如教育行业中的实验设备、建筑行业中的施工设备等)租赁或共享孵化的数字化管理工具,旨在融合数字化手段,提高各种设备器材的管理效率、确保设备的安全稳定运行,并优化资源使用及配置效率。随着高新技术的不断发展和应用(如大数据、人工智能等新......
  • 服务器数据库mysql error错误怎么解决
    解决MySQL错误通常需要根据具体的错误信息来定位问题并采取相应的措施。下面是一些常见的解决步骤,可以帮助你处理服务器数据库中的MySQL错误:查看错误日志:检查MySQL的错误日志文件,通常位于/var/log/mysql/error.log(Linux)或C:\ProgramData\MySQL\MySQLServer5.7\data\error.l......
  • 《深入浅出MySQL 数据库开发、优化与管理维护》第3版 阅读笔记
    第9章索引的设计和使用9.6索引在MySQL8.0中的改进不可见索引索引默认是可见的,可以在创建表时增加invisible关键字来创建不可见索引createtablet1(iint,jint,indexi_idx(i)invisiable)engine=InnoDB;createindexi_idxont1(i)invisiable;altertablet1ad......
  • EC2机器上MySQL8 修改关闭binlog以及修改保存时间
    从库清空binlog因为MySQL8.0要修改配置文件,在mysqld下面增加skip-log-bin,且需要重启,所以换种思路直接将其设置为3分钟。##单位秒setglobalbinlog_expire_logs_seconds=180;##flushlogs;showbinarylogs;##清理日志,别一下全删完了,删到倒数第二个purgebinarylogs......
  • 初始MYSQL数据库(6)—— 事务
    找往期文章包括但不限于本期文章中不懂的知识点:个人主页:我要学编程(ಥ_ಥ)-CSDN博客所属专栏: MYSQL目录事务的概念 事务的ACID特性使用事务查看支持事务的存储引擎 事务的语法 保存点 自动/手动提交事务事务的隔离性和隔离级别事务的概念 首先,得了解什......