当前位置: 首页 > 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…...

【论文阅读笔记】Tackling the Generative Learning Trilemma with Denoising Diffusion GANs

【论文阅读笔记】Tackling the Generative Learning Trilemma with Denoising Diffusion GANs Introduction方法 使用传统GANS建模去噪分布理解模式覆盖率 Paper&#xff1a;https://arxiv.org/abs/2112.07804 Code&#xff1a;https://github.com/NVlabs/denoising-diffusion-…...

常见 HTTP 状态码详解与Nginx 文件上传大小限制

在我们日常使用 Nginx 搭建网站或应用服务时&#xff0c;可能会遇到很多与文件上传和请求响应相关的问题。今天我们就来聊聊 如何限制文件上传的大小&#xff0c;并介绍一些常见的 HTTP 状态码 及其在 Nginx 中的处理方式。 一、文件上传大小限制 有时&#xff0c;我们需要限…...

在mac中使用numbers对数据进行分列(更详细的回答,已解决)

不想看我废话的同学直接看 “ 二、真正的方法 ” 不是抄袭不是抄袭&#xff0c;目前我能检索到的关于number分列的只有两篇回答&#xff0c;但我觉得有待补充&#xff0c;如果看不懂另外的回答&#xff0c;可以来看我的 这么问我猜大概率是Windows转macOS用户&#xff0c;不是…...

网格参数的应用和数学基础

引言 对于任意两个拓扑结构相似的表面&#xff0c;可以计算它们之间的一一对应映射。如果其中一个表面由三角形网格表示&#xff0c;那么计算这种映射的问题被称为网格参数化。映射到的表面通常被称为参数域。表面网格与各种域之间的参数化在计算机图形学和几何处理中有广泛的应…...

【Go】-基于Gin和GORM的小清单项目

目录 项目介绍 简介 技术 项目结构 项目分析 总结 项目介绍 简介 项目地址&#xff1a;knoci/list: 基于Gin的待办清单小项目 (github.com) 一个仿照github/Q1mi/bubble 做的一个gin框架练习 技术 gin 框架gorm 操作PostgreSQLini 配置文件 项目结构 list ├── R…...

【银河麒麟高级服务器操作系统】虚拟机服务器执行systemctl提示timeout——分析全过程及处理建议

了解更多银河麒麟操作系统全新产品&#xff0c;请点击访问 麒麟软件产品专区&#xff1a;https://product.kylinos.cn 开发者专区&#xff1a;https://developer.kylinos.cn 文档中心&#xff1a;https://documentkylinos.cn 现象描述 产品信息 产品名称 银河麒麟高级服务…...

【Unity错误】No cloud project ID was found by the Analytics SDK

在编译默认的URP 2D项目时&#xff0c;出现这样一个错误&#xff1a;No cloud project ID was found by the Analytics SDK. This means Analytics events will not be sent. Please make sure to link your cloud project in the Unity editor to fix this problem. 原因&…...

2. 变量和指令(omron 机器自动化控制器)——1

机器自动化控制器——第二章 变量和指令 1 2-1 变量一览表MC通用变量轴变量▶ 轴组变量 运动控制指令的输入变量输入变量的有效范围▶ 枚举体一览表 运动控制指令的输出变量运动控制指令的输入输出变量 2-1 变量一览表 MC功能模块使用的变量分为两类。 一类是监视轴等的状态及…...

gpt4最新保姆级教程

如何使用 WildCard 服务注册 Claude3 随着 Claude3 的震撼发布&#xff0c;最强 AI 模型的桂冠已不再由 GPT-4 独揽。Claude3 推出了三个备受瞩目的模型&#xff1a;Claude 3 Haiku、Claude 3 Sonnet 以及 Claude 3 Opus&#xff0c;每个模型都展现了卓越的性能与特色。其中&a…...

Java:继承和多态(1)

在 Java SE 中&#xff0c;继承和多态是面向对象编程&#xff08;OOP&#xff09;的两个核心概念。通过继承&#xff0c;子类可以复用父类的代码&#xff1b;而通过多态&#xff0c;子类可以在不修改父类的前提下定义自己的行为。这两者结合起来使得代码更具扩展性、灵活性和可…...