当前位置: 首页 > news >正文

MySQL学习(多表操作)

基本知识

一对多

  • 创建部门表 – 主表
create table if not exists dept(deptno varchar(20) primary key ,name varchar(20)
);
  • 创建员工表 – 创建外键约束 方式1constraint emp_fk foreign key(dept_id) references dept(deptno)
create table if not exists emp(eid varchar(20),ename varchar(20),age int,dept_id varchar(20),constraint emp_fk foreign key(dept_id) references dept(deptno)
);
  • 方式2alter table emp add constraint emp2_fk foreign key(dept_id) references dept(deptno);
  • 插入数据(从表添加数据时必须依赖主表的主键列)
-- 先给主表添加数据insert into dept values('1001','研发部');insert into dept values('1002','销售部');insert into dept values('1003','财务部');insert into dept values('1004','人事部');-- 从表添加数据时必须依赖主表的主键列insert into emp values('1','张三',20,'1001');insert into emp values('2','李四',21,'1001');insert into emp values('3','王五',23,'1001');insert into emp values('4','赵六',18,'1002');insert into emp values('5','钱七',35,'1002');insert into emp values('6','孙八',33,'1003');insert into emp values('7','周九',50,'1003');insert into emp values('8','吴十',45,'1004');insert into emp values('9','郑十一',30,'1005');
  • 删除emp表的数据delete from emp where dept_id='1004';
  • 当主表受依赖时不能删除delete from dept where deptno='1002'; -- 报错
  • 删除外键约束alter table emp drop foreign key emp_fk;

多对多(中间表是从表)

  • 创建学生表
create table if not exists student(sid int primary key auto_increment,name varchar(20),age int,gender varchar(20)
);
  • 创建课程表
create table if not exists course(cid int primary key auto_increment,cidname varchar(20)
);
  • 创建中间表
create table if not exists score(sid   int,cid   int,score double
);
  • 添加外键约束
alter table score add constraint score_fk1 foreign key (sid) references student(sid);
alter table score add constraint score_fk2 foreign key (cid) references course(cid);
  • 插入数据
-- 学生表insert into student values(null,'张三',20,'男'), (null,'李四',21,'男'), (null,'王五',23,'女');-- 课程表insert into course values(null,'语文'), (null,'数学'), (null,'英语');-- 中间表insert into score values(1,1,80), (1,2,90), (1,3,75), (2,1,70), (2,3,85), (3,2,95);

多表查询

  • 交叉连接查询,笛卡尔积(会产生大量冗余数据)select * from dept,emp;
  • 内连接查询 求多张表的交集
    隐式内连接select * from dept,emp where dept.deptno=emp.dept_id;
    显式内连接select * from dept inner join emp on dept.deptno=emp.dept_id;
    – 查询每个部门的所属员工select * from dept inner join emp on dept.deptno=emp.dept_id;
    – 查询研发部门的所属员工select * from dept inner join emp on dept.deptno=emp.dept_id and dept.name='研发部';
    – 查询每个部门的所属员工数量并升序排列select dept.name, count(*) from dept inner join emp on dept.deptno=emp.dept_id group by dept.name order by count(*);
    – 查询每个部门的所属员工数量大于等于2的并降序排列select dept.name, count(*) from dept inner join emp on dept.deptno=emp.dept_id group by dept.name having count(*) >= 2 order by count(*) desc;
  • 外连接查询(这里删除了外键约束)
	-- 左外连接(查询哪些部门有员工,哪些没有)select * from dept left outer join emp on dept.deptno=emp.dept_id;-- 右外连接(查询哪些员工属于哪个部门,哪些没有)select * from dept right outer join emp on dept.deptno=emp.dept_id;-- 全外连接(union)(查询所有部门和员工)select * from dept left outer join emp on dept.deptno=emp.dept_idunionselect * from dept right outer join emp on dept.deptno=emp.dept_id;
  • 子查询(select嵌套)
	-- 单行单列:返回具体列的内容,可以理解为一个单值数据-- 查询年龄最大的员工信息select * from emp where age = (select max(age) from emp);-- 单行多列:返回一行中多个列的数据-- 多行单列:返回多行中同一列的内容,相当于给出一个操作范围-- 查询研发部和销售部的员工信息select * from emp join dept on emp.dept_id = dept.deptno where (dept.name='研发部' or dept.name='销售部');  -- 关联查询select * from emp where dept_id in (select deptno from dept where name='研发部' or name='销售部');    -- 子查询-- 多行多列:返回的是一张临时表select * from emp join dept on emp.dept_id = dept.deptno where (emp.age > 20 and dept.name='研发部');select * from (select * from emp where age > 20) t1 join (select * from dept where name='研发部') t2 on t1.dept_id = t2.deptno;
  • 关键字
        -- ALL-- 查询年龄大于‘1001’部门的所有员工的信息select * from emp where age > all (select age from emp where dept_id = '1001');-- 查询不属于任何一个部门的员工的信息select * from emp where dept_id != all (select deptno from dept);-- ANY和some是等价的-- 查询年龄大于‘1001’部门的任意一个员工的信息select * from emp where age > any (select age from emp where dept_id = '1001');-- IN-- 查询研发部和销售部的员工信息select eid, ename from emp where dept_id in (select deptno from dept where name='研发部' or name='销售部');-- exists-- 查询是否有年龄大于40岁的员工,有则返回所有员工信息,否则返回空select * from emp a where exists(select * from emp where a.age > 40 );-- 查询有所属部门的员工信息select * from emp a where exists(select * from dept where dept.deptno = a.dept_id);
  • 自关联查询(必须给表起别名)
    准备数据
-- 创建表,建立自关联约束create table t_sanguo(eid int primary key,ename varchar(20),manager_id int, -- 外键列foreign key(manager_id) references t_sanguo(eid));-- 插入数据insert into t_sanguo values(1, '刘协', null);insert into t_sanguo values(2, '刘备', 1);insert into t_sanguo values(3, '关羽', 2);insert into t_sanguo values(4, '张飞', 2);insert into t_sanguo values(5, '曹操', 1);insert into t_sanguo values(6, '许褚', 5);insert into t_sanguo values(7, '典韦', 5);insert into t_sanguo values(8, '孙权', 1);insert into t_sanguo values(9, '周瑜', 8);insert into t_sanguo values(10, '鲁肃', 8);

进行关联查询

        -- 查询每个员工的姓名和直接上级的姓名select a.ename, b.ename from t_sanguo a inner join t_sanguo b on a.manager_id = b.eid;-- 查询每个员工的姓名和直接上级的姓名,如果员工没有上级,则显示nullselect a.ename, b.ename from t_sanguo a left join t_sanguo b on a.manager_id = b.eid;-- 查询每个员工的姓名和直接上级的姓名和间接上级的姓名selecta.ename, b.ename, c.enamefrom t_sanguo aleft join t_sanguo b on a.manager_id = b.eidleft join t_sanguo c on b.manager_id = c.eid;

练习

  • 准备数据(部门表,员工表,工资等级表)
create database test1;
use test1;
-- 创建部门表
create table dept(deptno int primary key, -- 部门编号dname varchar(14),      -- 部门名称loc varchar(13)         -- 部门所在地
);
insert into dept values (10, 'accounting', 'new york');
insert into dept values (20, 'researach', 'dallas');
insert into dept values (30, 'sales', 'chicago');
insert into dept values (40, 'operations', 'boston');
-- 创建员工表
create table emp(empno int primary key, -- 员工编号ename varchar(10),     -- 员工姓名job varchar(9),        -- 工作mgr int,               -- 上级编号hiredate date,         -- 入职日期sal double,            -- 薪水comm double,          -- 奖金deptno int            -- 对应dept表的外键
);
-- 添加部门与员工之间的主外键关系
alter table emp add constraint foreign key emp(deptno) references dept(deptno);insert into emp values (7369, 'smith', 'clerk', 7902, '1980-12-17', 800, null, 20);
insert into emp values (7499, 'allen', 'salesman', 7698, '1981-02-20', 1600, 300, 30);
insert into emp values (7521, 'ward', 'salesman', 7698, '1981-02-22', 1250, 500, 30);
insert into emp values (7566, 'jones', 'manager', 7839, '1981-04-02', 2975, null, 20);
insert into emp values (7654, 'martin', 'salesman', 7698, '1981-09-28', 1250, 1400, 30);
insert into emp values (7698, 'blake', 'manager', 7839, '1981-05-01', 2850, null, 30);
insert into emp values (7782, 'clark', 'manager', 7839, '1981-06-09', 2450, null, 10);
insert into emp values (7788, 'scott', 'analyst', 7566, '1987-04-19', 3000, null, 20);
insert into emp values (7839, 'king', 'president', null, '1981-11-17', 5000, null,10);
insert into emp values (7844, 'turner', 'salesman', 7698, '1981-09-08', 1500, 0, 30);
insert into emp values (7876, 'adams', 'clerk', 7788, '1987-05-23', 1100, null, 20);
insert into emp values (7900, 'james', 'clerk', 7698, '1981-12-03', 950, null, 30);
insert into emp values (7902, 'ford', 'analyst', 7566, '1981-12-03', 3000, null, 20);
insert into emp values (7934, 'miller', 'clerk', 7782, '1982-01-23', 1300, null, 10);-- 创建工资等级表
create table salgrade(grade int, -- 工资等级losal double,  -- 最低工资hisal double   -- 最高工资
);
insert into salgrade values (1, 700, 1200);
insert into salgrade values (2, 1201, 1400);
insert into salgrade values (3, 1401, 2000);
insert into salgrade values (4, 2001, 3000);
insert into salgrade values (5, 3001, 9999);
  • 1.返回拥有员工的部门名与部门编号
select dept.dname, dept.deptno from dept where (select count(*) from emp where dept.deptno = emp.deptno) > 0;
select distinct dept.dname, dept.deptno from dept inner join emp on dept.deptno = emp.deptno;
  • 2.返回工资比smith高的员工信息
select * from emp where sal > (select sal from emp where ename = 'smith');
  • 3.返回员工和所属经理的姓名
select a.ename, b.ename from emp a, emp b where a.mgr = b.empno;
  • 4.返回入职时间早于经理的员工的姓名和经理姓名
select a.ename, b.ename from emp a, emp b where a.mgr = b.empno and a.hiredate < b.hiredate;
  • 5.返回员工姓名和部门名
select emp.ename, dept.dname from dept, emp where dept.deptno = emp.deptno;
  • 6.返回所有clerk员工的姓名和部门名
select emp.ename, dept.dname from dept join emp on dept.deptno = emp.deptno where emp.job = 'clerk';
  • 7.返回部门编号、最低工资
select emp.deptno, min(sal) from emp group by emp.deptno;
  • 8.返回sales部门的员工的姓名
select emp.ename from emp where emp.deptno = (select deptno from dept where dname = 'sales');
  • 9.返回平均工资高于所有员工平均工资的员工
select * from emp where emp.sal > (select avg(sal) from emp);
  • 10.返回与scott同一职位的员工
select * from emp where emp.job = (select job from emp where emp.ename = 'scott') and emp.ename != 'scott';
  • 11.返回工资高于部门30所有员工的员工
select * from emp where emp.sal > all (select sal from emp where emp.deptno = 30);
  • 12.返回每个职位的最低工资
select job, min(sal) from emp group by job;
  • 13.返回年薪并排序
select emp.ename, 12 * sal + ifnull(comm, 0) from emp order by (12 * sal + ifnull(comm, 0)) desc ;
  • 14.返回工资在等级4的员工
select a.ename from emp a join salgrade b on (a.sal between b.losal and b.hisal) and b.grade = 4;
  • 15.返回工资在等级2的员工的姓名和部门所在地
select a.ename, b.loc from emp a, dept b, salgrade c where (a.sal between c.losal and c.hisal) and c.grade = 2 and a.deptno = b.deptno;

相关文章:

MySQL学习(多表操作)

基本知识 一对多 创建部门表 – 主表 create table if not exists dept(deptno varchar(20) primary key ,name varchar(20) );创建员工表 – 创建外键约束 方式1constraint emp_fk foreign key(dept_id) references dept(deptno) create table if not exists emp(eid varc…...

鸿蒙开发(NEXT/API 12)【网络连接管理】 网络篇

简介 网络连接管理提供管理网络一些基础能力&#xff0c;包括WiFi/蜂窝/Ethernet等多网络连接优先级管理、网络质量评估、订阅默认/指定网络连接状态变化、查询网络连接信息、DNS解析等功能。 说明 为了保证应用的运行效率&#xff0c;大部分API调用都是异步的&#xff0c;对…...

VMware Fusion虚拟机Mac版 安装Ubuntu操作系统教程

Mac分享吧 文章目录 下载镜像地址&#xff1a;[www.macfxb.cn](http://www.macfxb.cn)一、CentOS安装完成&#xff0c;软件打开效果二、Mac中安装Ubuntu虚拟机1️⃣&#xff1a;下载镜像2️⃣&#xff1a;创建虚拟机3️⃣&#xff1a;虚拟机设置4️⃣&#xff1a;虚拟机安装5️…...

基于SpringBoot+Vue+MySQL的房屋租赁管理系统

系统展示 用户前台界面 管理员后台界面 系统背景 二十一世纪互联网的出现&#xff0c;改变了几千年以来人们的生活&#xff0c;不仅仅是生活物资的丰富&#xff0c;还有精神层次的丰富。在互联网诞生之前&#xff0c;地域位置往往是人们思想上不可跨域的鸿沟&#xff0c;信息的…...

虚拟机器配置固定IP地址

新安装的虚拟机&#xff0c;如何配置固定的ip地址&#xff0c;废话少说直接上干货 第一步&#xff1a;在VMarea中 选中你要固定IP的虚拟机器&#xff0c;点击上面的“编辑”按钮&#xff0c;然后找到“虚拟网络编辑器”&#xff0c;选中你要修改的ip VMnet8&#xff0c;然后是…...

用python实现基于形态学的方法,如开运算和闭运算,来去除pcd格式激光点云中的植被

在Python中&#xff0c;你可以使用open3d库来读取和处理pcd格式的点云数据。下面是一个示例代码&#xff0c;展示如何使用形态学操作来去除植被。 首先&#xff0c;确保你已经安装了open3d库&#xff0c;可以使用以下命令进行安装&#xff1a; pip install open3d接下来&…...

QT 绘制简易时钟

原文件 #include "widget.h" #include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget) {ui->setupUi(this);this->startTimer(1000); }Widget::~Widget() {delete ui; }//时钟底座 void Widget::paintEvent(Q…...

为控制器的方法添加必要参数

前言&#xff1a;做这个系统时&#xff0c;要求每次调用接口时要传操作人、操作人电脑ip、菜单id&#xff0c;然后计入log。本来前端读取到然后加入请求头&#xff0c;后端写入log即可。但是老大要求后端也要把控必传参数&#xff0c;避免前端忘记。所以就写了这个。IOperation…...

(计算机网络)应用层

1.为什么需要应用层 应用层提供使用tcp&#xff0c;udp使用的方式 协议就是制定的规则 2.域名服务器概述 域名是唯一的 新增域名&#xff0c;大家都要修改这个文本文件&#xff0c;所以要进行集中管理这个文本文件&#xff0c;而不是使用本地的hosts文件 hosts文件在Windows系统…...

使用3DUNet训练自己的数据集(pytorch)— 医疗影像分割

代码:lee-zq/3DUNet-Pytorch: 3DUNet implemented with pytorch (github.com) 文章<cicek16miccai.pdf (uni-freiburg.de)3D U-Net: Learning Dense Volumetric Segmentation...

【python】—— Python爬虫实战:爬取珠海市2011-2023年天气数据并保存为CSV文件

目录 目标 准备工作 爬取数据的开始时间和结束时间 爬取数据并解析 将数据转换为DataFrame并保存为CSV文件 本文将介绍如何使用Python编写一个简单的爬虫程序,以爬取珠海市2011年至2023年的天气数据,并将这些数据保存为CSV文件。我们将涉及到以下知识点: 使用r…...

U盘文件及文件夹带锁修复

磁盘管理修复工具Disks磁盘管理–针对U盘文件及文件夹带锁修复 本文章只针对统信系统 文章目录 功能概述一、安装工具二、数据备份三、检查文件系统1. 通过启动栏中的“磁盘”或者桌面的“磁盘”启动文件来启动应用:2. 选择U盘设备3. 点击“检查文件系统”按钮(如果无此按钮…...

AnyChart 数据可视化框架

AnyChart 数据可视化框架 AnyChart 是一个灵活的 JavaScript&#xff08;HTML5、SVG、VML&#xff09;图表框架&#xff0c;适合任何需要数据可视化的解决方案。 目录 下载并安装开始插件将 AnyChart 与 TypeScript 结合使用将 AnyChart 与 ECMAScript 6 结合使用技术集成贡献…...

ARM base instruction -- br

BR Branch to Register branches unconditionally to an address in a register, with a hint that this is not a subroutine return. 无条件地分支到寄存器中的一个地址&#xff0c;并提示这不是子例程返回。 BR <Xn> BR 跳转到reg内容地址&#xff0c;不会将返回地址…...

编译原理/软件工程核心概念-问题理解

目录 1.程序的编译执行过程 2.指针和引用的区别 3.堆和栈的区别 4.最熟悉的编程语言- Python&#xff1a;介绍PyTorch和TensorFlow框架 5.C与C的区别 6.软件工程是什么&#xff1f; 7.简述瀑布模型 8.敏捷开发方法是什么&#xff1f;它与瀑布模型相比有哪些优势和劣势 1…...

学习pyqt5相关知识回顾

1. 模块 1.1 import导入 1) 模块:是一系列功能的集合体,模块名.功能名,就可以使用模块的功能 2) 首次导入模块,就会立即执行模块里面的内容 3) 当前名称空间会产生一个名字module,指向module.py产生的名称空间.我们可以使用module.name/函数名,来调用module.py里面的内容. …...

OPENAIGC开发者大赛高校组银奖 | LonAC中小学编程学习平台

在第二届拯救者杯OPENAIGC开发者大赛中&#xff0c;涌现出一批技术突出、创意卓越的作品。为了让这些优秀项目被更多人看到&#xff0c;我们特意开设了优秀作品报道专栏&#xff0c;旨在展示其独特之处和开发者的精彩故事。 无论您是技术专家还是爱好者&#xff0c;希望能带给您…...

oneclick 命令:快速筛选控制变量的利器

目录 1. 命令语法2. 结果输出3. 使用示例4. 总结 在进行回归分析时&#xff0c;选择合适的控制变量对于确保模型的稳健性至关重要。然而&#xff0c;手动筛选变量组合不仅费时费力&#xff0c;还容易出错。为此&#xff0c;Stata 中的 oneclick 命令提供了一个高效的解决方案&a…...

Kotlin 代替Java接口回调,就这么简单

假如你使用旧的接口回调&#xff1a; 通常三步&#xff1a;1 定义接口和方法&#xff1b;2 使用接口中方法&#xff1b;3 继承接口并实现方法&#xff1b; 例&#xff1a; class XXXAdapter{public var mClickCollBack: clickCollBack? null //1定义interface clickColl…...

Codeforces Round 971 (Div. 4)——C题题解

本题的大意是一个青蛙从原点开始跳格子(0,0)&#xff0c;最终要跳到点(x,y)去&#xff0c;并且每一步的步长不能超过k&#xff0c;问最短几步可以跳到终点 分析&#xff1a; 本题利用贪心思想&#xff0c;肯定是先跳最大的步长这样总体用的步数最长 代码演示&#xff1a; #inc…...

手游刚开服就被攻击怎么办?如何防御DDoS?

开服初期是手游最脆弱的阶段&#xff0c;极易成为DDoS攻击的目标。一旦遭遇攻击&#xff0c;可能导致服务器瘫痪、玩家流失&#xff0c;甚至造成巨大经济损失。本文为开发者提供一套简洁有效的应急与防御方案&#xff0c;帮助快速应对并构建长期防护体系。 一、遭遇攻击的紧急应…...

k8s从入门到放弃之Ingress七层负载

k8s从入门到放弃之Ingress七层负载 在Kubernetes&#xff08;简称K8s&#xff09;中&#xff0c;Ingress是一个API对象&#xff0c;它允许你定义如何从集群外部访问集群内部的服务。Ingress可以提供负载均衡、SSL终结和基于名称的虚拟主机等功能。通过Ingress&#xff0c;你可…...

Mybatis逆向工程,动态创建实体类、条件扩展类、Mapper接口、Mapper.xml映射文件

今天呢&#xff0c;博主的学习进度也是步入了Java Mybatis 框架&#xff0c;目前正在逐步杨帆旗航。 那么接下来就给大家出一期有关 Mybatis 逆向工程的教学&#xff0c;希望能对大家有所帮助&#xff0c;也特别欢迎大家指点不足之处&#xff0c;小生很乐意接受正确的建议&…...

c++ 面试题(1)-----深度优先搜索(DFS)实现

操作系统&#xff1a;ubuntu22.04 IDE:Visual Studio Code 编程语言&#xff1a;C11 题目描述 地上有一个 m 行 n 列的方格&#xff0c;从坐标 [0,0] 起始。一个机器人可以从某一格移动到上下左右四个格子&#xff0c;但不能进入行坐标和列坐标的数位之和大于 k 的格子。 例…...

ESP32 I2S音频总线学习笔记(四): INMP441采集音频并实时播放

简介 前面两期文章我们介绍了I2S的读取和写入&#xff0c;一个是通过INMP441麦克风模块采集音频&#xff0c;一个是通过PCM5102A模块播放音频&#xff0c;那如果我们将两者结合起来&#xff0c;将麦克风采集到的音频通过PCM5102A播放&#xff0c;是不是就可以做一个扩音器了呢…...

DIY|Mac 搭建 ESP-IDF 开发环境及编译小智 AI

前一阵子在百度 AI 开发者大会上&#xff0c;看到基于小智 AI DIY 玩具的演示&#xff0c;感觉有点意思&#xff0c;想着自己也来试试。 如果只是想烧录现成的固件&#xff0c;乐鑫官方除了提供了 Windows 版本的 Flash 下载工具 之外&#xff0c;还提供了基于网页版的 ESP LA…...

Java 二维码

Java 二维码 **技术&#xff1a;**谷歌 ZXing 实现 首先添加依赖 <!-- 二维码依赖 --><dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.5.1</version></dependency><de…...

快刀集(1): 一刀斩断视频片头广告

一刀流&#xff1a;用一个简单脚本&#xff0c;秒杀视频片头广告&#xff0c;还你清爽观影体验。 1. 引子 作为一个爱生活、爱学习、爱收藏高清资源的老码农&#xff0c;平时写代码之余看看电影、补补片&#xff0c;是再正常不过的事。 电影嘛&#xff0c;要沉浸&#xff0c;…...

Golang——9、反射和文件操作

反射和文件操作 1、反射1.1、reflect.TypeOf()获取任意值的类型对象1.2、reflect.ValueOf()1.3、结构体反射 2、文件操作2.1、os.Open()打开文件2.2、方式一&#xff1a;使用Read()读取文件2.3、方式二&#xff1a;bufio读取文件2.4、方式三&#xff1a;os.ReadFile读取2.5、写…...

消防一体化安全管控平台:构建消防“一张图”和APP统一管理

在城市的某个角落&#xff0c;一场突如其来的火灾打破了平静。熊熊烈火迅速蔓延&#xff0c;滚滚浓烟弥漫开来&#xff0c;周围群众的生命财产安全受到严重威胁。就在这千钧一发之际&#xff0c;消防救援队伍迅速行动&#xff0c;而豪越科技消防一体化安全管控平台构建的消防“…...