MySQL Study Guide & Notes & Classic Case Sentences

Author: BSXY_19 Jike_Chen Yongyue
BSXY_School of Information
Note: Reposting any content without permission is prohibited

This article is a learning note or guide about MySQL. There are many classic cases in this article for corresponding exercises and references. In the future, articles about database systems will be continuously updated.

0. Comprehensive case of MySQL (you don’t need to read it)

Regarding the comprehensive case, you can consult and learn from this article, and the corresponding questions and sql sentences are attached:
MySQL comprehensive application practice (directly copy to your own space),
and more corresponding articles will be updated later
insert image description here

1. Database operation (DDL)

Inquire:

#查询所有数据库:
show databases;
---------------------------------

#查询当前数据库:
select database();

create:

#创建数据库
create database [if not exists] 数据库名 [default charset 字符集][collate 排序规则];
#:如1:
create database if not exists test default charset utf8mb4;
#如2:
CREATE DATABASE IF NOT EXISTS RUNOOB DEFAULT CHARSET utf8 COLLATE utf8_general_ci;

delete:

#删除数据库
drop database [if exists] 数据库名;
#如:
drop database if exists test;

use:

#使用数据库:
use 数据库名;

2. Table operation (DDL)

Inquire:

#查询当前数据库所有表
show tables;
-------------------------

#查询表结构
desc 表名;
-------------------------

#查询指定表的建表语句/表的详细信息
show create table 表名;

Create table:

create table 表名(
    字段1;字段1类型[comment 字段1注释],
    字段2;字段2类型[comment 字段2注释],
    ................................
    字段n;字段n类型[comment 字段n注释]
)[comment 表注释];
id name age gender
1 Zhang San 28 male
2 Li Si 60 male
3 Wang Wu 32 female
#创建上表:
create table tb_user(
id int comment '编号',
name varchar(50) comment '姓名',
age int comment '年龄',
gender varchar(2) comment '性别'
)comment '用户表';

Modify table:

#修改表名:
alter table tb_user rename to usm;

drop table:

#删除表
drop table [if exists] 表名;
-------------------------

#删除指定表,并重新创建该表(只删除数据留结构了解)
truncate table 表名;

Add fields:

alter table 表名 add 字段名 类型(长度) [comment 注释][约束];
#如:
alter table tb_user add nickname varchar(20) comment '昵称';

Modify fields:

#修改数据类型:
alter table 表名 modify 字段名 新数据类型(长度);
-------------------------

#修改字段名和字段类型
alter table 表名 change 旧字段名 新字段名 类型(长度)[comment 注释][约束]
#如:
alter table tb_user change nickname username vatchar(30) comment '用户名';

Delete field:

alter table 表名 drop 字段名;
#如:
alter table tb_user drop username;

3. Data manipulation (DML)

adding data:

#给指定数据添加数据:
insert into 表名(字段名1,字段名2,...)values(1,2,...)
#如:
insert into usm(id,name,age,gender,username)values(1,'张三',19,'男','小三');
-------------------------

#给全部字段添加数据:
insert into 表名 values(1,2,...)
#如:
insert into usm values(1,'张三',19,'男','小三');
-------------------------

#批量添加数据:
insert into 表名 (字段名1,字段名2,...) values(1,2,...),(1,2...),(1,2,...);
insert 表名 values (1,2,...),(1,2...),(1,2,...);

change the data:

update 表名 set 字段名1=1,字段名2=2,...[where 条件];
#如1:
update usm set username='小五' where id=2;
#如2:
update usm set username='小赵',gender='女' where id=2;
#如3:
update usm set username='小五';#更新整张表的username字段为小五

delete data:

delete from 表名 [where 条件];
#如1:
delete from usm where gender='女';#删除gender为女的数据字段:
#如2:
delete from usm #删除所有表的数据

Inquire:

#查询整个表:
select * from 表名;
#如:
select * from usm;

4. Query (DQL)

select
	字段列表
from
	表名列表
where
	条件列表
group by
	分组字段列表
having
	分组后条件列表
order by
	排序字段列表
limit
	分页参数

1. Basic query

#查询多字字段
select 字段1,字段2,... from 表名;
select * from 表名;
#如:
select name,age from usm;
--------------------------------

#设置别名
select 字段1[as 别名1],字段2[as 别名2]...from 表名;
#如:
select name as '名字' from usm;
-------------------------

#去除重复记录
select distinct 字段列表 from 表名;
#如:
select distinct name from usm;

2. Condition query

select 字段列表 from 表名 where 条件列表;
-------------------------------------------
	条件:
比较运算符				功能
>						大于
>=						大于等于
<						小于
<=						小于等于
=						等于
<>!=				    不等于
between..and..			 在某个范围之内
in(...)in之后的列表中的值,多选一
link 占位符			  模糊匹配(_匹配单个字符,%匹配任意个字符)
is nullnull

逻辑运算符:
and&&					并且
or||					或者
not!					非不是
------------------------------------------
#查询年龄等于80的人信息
select * from emp where age=80;

#查询没有写age的人的信息
select * from emp where idcare is null;

#查询写了aged的人的信息
select * from emp where idcare is not null;

#查询年龄不等于88的年龄的人的信息
select * from emp where age !=88;
select * from emp where age <> 88;

#查询年龄在15(包含)到20(包含)的年龄的人的信息
select * from emp where age >=15 && age<=20;
select * from emp where age >=15 and age<=20;
select * from emp where between 15 and 20;

#查询性别为女且年龄小于25岁的员工信息
select * from emp where gender='女' and age<25;

#查询年龄等于18或20或40的员工信息
select * from emp where age=18 or age=20 or age=40;
select * from emp where age in(18,20,40);

#查询姓名为2个字的员工信息
select * from emp where name like '__';

#查询身份证最后一位是X的员工信息
select * from emp where idcard like '%X';

3. Aggregation function

将一列数据作为一个整体,进行纵向计算
函数			功能
count		   统计数量
max			   最大值
min			   最小值
avg			   平均值
sum			   求和
--------------------------------
select 聚合函数(字段列表) from 表名;#所有的null是不参与计算的

#统计员工数量
select count(id) from usm;
select count(*) from usm;

#统计员工平均年龄
select avg(age) from usm;

#统计西安地区员工年龄之和
select sum(age) from usm where workaddress='西安';

4. Group query

select 字段列表 from 表名 [where 条件] group by 分组字段名 [having 分组后过滤条件]
-------------------------------
wherehaving区别
1.执行时机不同: where是 分组之前 进行过滤,不满足where条件,不参与分组;having是 分组之后 对结果进行过滤。
2.判断条件不同: where不能对聚合函数进行判断,而having可以。
-------------------------------
#根据性别分组,统计男性员工和女性员工的数量
select gender,count(*) from emp group by gender;

#根据性别分组,统计男性员工和女性员工的平均年龄
select gender,avg(age) from emp group by gender;

#查询年龄小于40的员工,并根据工作地址分组,获取员工数量(count获得的值)大于等于3的工作地址
select workaddress,count(*) from emp where age<40 group by workaddress having count(*)>=3;

5. Sort query

select 字段列表 from 表名 order by 字段1 排序方式1,字段2 排序方式2;
排序方式: asc:升序 desc:降序
--------------------------
#根据年龄对员工进行升序排序
select * from emp order by age=asc;

#根据年龄对员工进行升序排序,年龄相同,在按照入职时间进行降序排序
select * from emp order by age=asc,emdate desc;

6. Paging query

select 字段列表 from 表名 limit 起始索引,查询记录数;
-------------------------------------
#查询第1页员工数据,每页展示10条记录
select * from emp limit 0,10;

#查询第2页员工数据,每页展示10条记录---->起始索引计算:(页码-1)*页展示记录数
select * from emp limit 10,10;

7. Comprehensive exercises

#查询年龄为20,21,23岁的女性员工
select * from emp where gender='女' and age in(20,21,23);

#查询性别为男,且年龄在20-40(含)以后的姓名为三个字的员工
select * from emp where gender='男' and age between 20 and 40 and name like '___';

#统计员工表中,年龄小于60岁的,男性员工和女性员工的人数
select gender,count(*) from emp where age<60 group by gender;

#根据年龄小于等于35岁员工的姓名和年龄,对年龄进行升序排序,年龄相同,在按照入职时间进行降序排序
select name,age from emp where age<=35 order by age=asc,emdate desc;

#查询性别为男,且年龄在20-40(含)岁以内的前5个员工信息,对查询的结果按照年龄升序排序,年龄相同按入职时间升序排序
select * from emp where gender='男' and age between 20 and 40 order by age aes,emdate ses limit 5;

5. User management (DCL)

#查询mysql数据库中的用户
use mysql;
select * from user;
------------------------------------

#创建用户
create user '用户名'@'主机名' identified by '123456';#@前后不能有空格
#如:
create user 'it'@'localhost' identified by '123456';
------------------------------------

#修改用户
alter user '用户名'@'主机名' identified with mysql_native_password by '新密码';
#如:
alter user 'it'@'localhost' identified with mysql_native_password by '1234';
------------------------------------

#删除用户
drop user '用户名'@'主机名';

6. User management (DCL)

---------------------------------
权限列表			 说明
all,all privileges  所有权限
select			   查询数据
insert			   插入数据
update			   修改数据
delete			   删除数据
alter			   修改表
drop			   删除数据库//视图
create			   创建数据库/---------------------------------
#查询权限
show grants for '用户名'@'主机名';
#如:
show grants for 'it'@'localhost';
---------------------------------

#授予权限,多个权限用逗号分隔
grant 权限列表 on 数据库.表名 to '用户名'@'主机名';
#如:*表示所有的
grant all on test.* to 'it'@'localhost';
---------------------------------

#撤销权限
revoke 权限列表 on 数据库.表名 from '用户名'@'主机名';
#如:
revoke all on test.* from 'it'@'localhost';

7. Function

1. String functions

function Function
concat(s1,s2,…sn) String splicing, splicing s1, s2...sn into a string
lower(str) Convert the string str to all lowercase
upper(str) Convert the string str to all uppercase
lpad(str,n,pad) Left padding, fill the left side of str with the string pad to reach the length of n strings
rpad(str,n,pad) Right padding, fill the right side of str with the string pad to reach the length of n strings
trim(str) Remove leading and trailing spaces from a string
substring(str,star,len) Returns a string of len lengths starting from the start position of the string str
select 函数;
#如:
select concat('hello','mysql');
select lower('Hello');
select lpad('01',5,'-');#---01
select trim(' Hello mysql ');
select substring('Hello mysql',1,5);

#案例如:
#需求变更,员工工号统一为5位数,目前不到5位数的全部在前面补0,比如:1号员工的工号就是00001
update emp set workno=lpad(workno,5,'0');

2. Numerical functions

function Function
celt(x) Rounded up
floor(x) round down
mod(x,y) Returns the modulus of x/y
rand() Returns a random number within 0-1
round(x,y) Find the rounded value of the parameter x, leaving y as a decimal
select ceil(1.1);#2
select mod(7,4)
select round(2.345,2)#2.35

#如:通过数据库函数,生成一个六位数的随机验证码
select lpad(round(rand()*1000000,0),6,'0');

3. Date function

function Function
curdate() return current date
curtime() return current time
now() returns the current date and time
year(date) Get the year of the specified date
month(date) Get the month of the specified date
day(date) Get the date of the specified date
date_add(date,interval expr type) Returns a date/time value plus a time value after the interval expr
datediff(date1,date2) Returns the number of days between the start time date1 and the end time date2
select curdate();#2023-10-11
select year(now());#2023
select date_add(now(),interval 70 day);#往后推70天的日期
select datediff('2021-12-01','2021-11-01')#两个日期的间隔,第一个时间减第二个时间

#如:查询所有员工的入职天数,并根据入职天数倒序排序
select name,datediff(curdate(),emdate) as 'bieming' from emp order by bieming desc;

4. Process control function

function Function
if(value,t,f) If value is true, return t, otherwise return f
ifnull(value1,value2) If value1 is not empty, return value1, otherwise return value2
case when [val1] then [res1]…else [default] end If val1 is true, return res1, ... otherwise return the default default value
case [expr] when [val1] then [res1]…else [default] end If the value of expr is equal to val1, return res1, ... otherwise return the default default value
select if(true,'OK','ERROR')

#如:查询emp表的员工的姓名和工作地址(北京/上海-->一线城市),其他-->二线城市
select
name,
(case workaddress when '北京' then '一线城市' when '上海' then '一线城市' else '二线城市' end) as '工作地址'
from emp;

#统计班级学员的成绩,>=85展示优秀,>=60展示及格,否则展示不及格
select
id,
name,
(case when math>=85 then '优秀' when math>=60 then '及格' else '不及格' end) as '数学',
(case when english>=85 then '优秀' when english>=60 then '及格' else '不及格' end) as '英语',
(case when chinese>=85 then '优秀' when chinese>=60 then '及格' else '不及格' end) as '语文'
from score;

8. Common constraints & cases

constraint describe keywords
not-null constraint Restrict the data of this field to not be null not null
unique constraint Ensure that all data in this field is unique and not repeated unique
primary key constraint The primary key is the unique identifier of a row of data, which requires non-null and unique primary key
default constraints When saving data, if the value of this field is not specified, the default value will be used default
check constraints Ensure that the field value satisfies a certain condition check
foreign key constraints It is used to establish a connection between the data of the two tables to ensure the consistency and integrity of the data foreign key

Cases (creating the following table) such as:

field name field meaning Field Type Restrictions constraint keyword
id id unique identification int Primary key, and auto-increment primary key,auto_increment
name Name varchar(10) is not empty and unique not null,unique
age age int Greater than 0 and less than or equal to 120 check
status state char(1) If this value is not specified, it defaults to 1 default
gender gender char(1) none
create table user(
id int primary key auto_increment comment '主键',
name varchar(10) not null unique comment '姓名',
age int check(age>0 && age<=120) comment '年龄',
status char(1) default '1' comment '状态',
gender char(1) comment '性别'
)comment '用户表';

9. Foreign key constraints & operations

#添加外键:
alter table 表名 add constraint 外键名称 foreign key(外键字段名) references 主表(主表列名);
#如:
alter table emp add constraint fk_emp_dept_id foreign key(dept_id) references dept(id);
--------------------------------------------

#删除外键:
alter table 表名 drop foreign key 外键名称;
#如:
alter table emp drop foreign key fk_emp_dept_id;
--------------------------------------------
Behavior illustrate
no action When deleting/updating the corresponding record in the parent table, first check whether the record has a corresponding foreign key, and if so, delete/update is not allowed. (consistent with RESTRICT) (default)
restrict When deleting/updating the corresponding record in the parent table, first check whether the record has a corresponding foreign key, and if so, delete/update is not allowed. (consistent with NO ACTION) (default)
cascade When deleting/updating the corresponding record in the parent table, first check whether the record has a corresponding foreign key, and if so, delete/update the record of the foreign key in the child table (if the parent table is changed, the child table will also be changed)
set null When deleting the corresponding record in the parent table, first check whether the record has a corresponding foreign key, and if so, set the foreign key value in the child table to null (the premise is that the foreign key is allowed to be null) (the parent table is changed to the child table. to null)
#添加外键且更新时行为,如:
alter table 表名 add constraint 外键名称 foreign key(外键字段名) references 主表(主表列名) on update cascade on delete cascade;

alter table 表名 add constraint 外键名称 foreign key(外键字段名) references 主表(主表列名) on update set null on delete set null;

10. Multi-table query

1. Multi-table query

#如:
select * from emp,dept where emp.dept_id=dept.id

2. Inner connection

内连接查询的是两张表交集的部分

#隐式内连接
select 字段列表 from1,表2, where 条件...;
#如:查询每一个员工的姓名,及关联的部门的名称(隐式内连接)
select emp.name,dept.name from emp,dept where emp.dept_id=dept.id
#如果表名太长可以起 别名 如下:
select e.name,d.name from emp e,dept d where e.dept_id=d.id;
#如:查询拥有员工的部门ID、部门名称
select distinct d.id,d.name from emp e,dept d where e.dept_id=d.id;#distinct:去重
#如:查询所有员工的工资等级
select e.*,s.grade,s.losal,s.hisal from emp e,salgrade s where e.salary>=s.losal and e.salary<=s.hisal;
-----------------------------------
#如:查询"研发部"所有员工的信息及工资等级
#表:emp,salgrade,dept
#连接条件:emp.salary between salgrade.losal and salgrade.hisal,emp.dept_id=dept.id
#查询条件:dept.name='研发部'
select e.*,s.grade from emp e,dept d,salarade s where e.dept_id=d.id and (e.salary between s.losal and s.hisal) and d.name ='研发部';
-----------------------------------
#如:查询所有学生的选课情况,展示出学生名称,学号,课程名称
#表:student,course,student_course
#连接条件:student.id=student_course.studentid,course.id=student_course.courseid
select s.name,sno,c.name from student s,student_course sc,course c where s.id=sc.studentid and sc.courseid=c.id;
-----------------------------------

#显示内连接
select 字段列表 from1 [inner] join2 on 连接条件...;
#如:查询每一个员工的姓名,及关联的部门的名称(显式内连接)inner可以省略
select e.name,d.name from emp e inner join dept d on e.dept_id=d.id; 
#如:查询年龄小于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. Outer connection

#左外连接:
select 字段列表 from1 left [outer] join2 on 条件...;
#相当于查询表1的所有数据包含表1和表2的交集部分的数据
#如:查询emp表中的所有数据,和应的部门信息(左连接)
select e.* d.name from emp e left outer join dept d on e.dept_id=d.id;
-----------------------------------------

#右外连接:
select 字段列表 from1 left [outer] join2 on 条件...;
#如:查询dept表的所有数据,和对应的员工信息(右连接)
select d.*,e.* from emp e right outer join dept d on e.dept_id=d.id;
#改为左连接:
select d.*,e.* from dept d left outer join emp e on e.dept_id=d.id;

#一般都用左连接

4. Self-connection

#可以理解为自己查自己,可以是 内连接查询 也是可以是 外连接查询
select 字段列表 from 表A 别名A join 表A 别名B on 条件...;
#如:查询员工 及其 所有领导的名字
select a.name, b.name from emp a,emp b where a.managerid=b.id;

#如:查询所有员工(emp)及其领导的名字(emp),如果员工没有领导,也需要查询出来;
select a.name '员工',b.name '领导' from emp a left join emp b on a.managerid=b.id;

5. Joint query

#就是把多次查询的结果合并起来,合并形成一个新的查询结果集
#1、多张表的列数必须保持一致
#2、union all会将全部的数据合并在一起,union会对合并之后的数据去重
select 字段列表 from 表A...
union [all]
select 字段列表 from 表B...;
#如:在emp中查询薪资低于5000的员工,和年龄大于50岁的员工全部查询出来
select * from emp where salary<5000
union all
select * from emp where age>50;
#如果需要合并的结果去重的话就把all去了

6. Sub (nested) queries

According to the subquery results, it is divided into:
1. Scalar subquery (the result of the subquery is a single value)
2. Column subquery (the result of the subquery is a column)
3. Row subquery (the result of the subquery is a row)
4. Table subquery ( The result of the subquery is multiple rows and multiple columns)
According to the position of the subquery, it is divided into: after where, after from, and after select
Scalar query:

#标量子查询返回的结果是单个值(数字、字符串、日期等),常用的操作符:= <> > >= < <=
#如:查询"销售部"的所有员工信息
#a.查询"销售部"部门ID
select id from dept where name='销售部';
#b.根据销售部部门ID,查询员工信息
select * from emp where dept_id=4;
#合并为:
select * from emp where dept_id=(select id from dept where name='销售部');
------------------------------------------

#如:查询在"小明"入职之后的员工信息
#a.查询小明的入职日期
select emdate from emp where name='小明';
#b.查询入职日期之后入职的员工
select * from emp where emdate >'XXXX-XX-XX';
#合并:
select * from emp where emdate > (select emdate from emp where name='小明');

Column query:

#常用的操作符:in、not in、any、some、all
操作符				描述
in				在指定的集合范围之内,多选一
not in			不在指定的集合范围之内
any				子查询返回列表中,有任意一个满足即可
someany等同,使用some的地方都可以使用any
all				子查询返回列表的 所有值都必须满足 
--------------------------------------------------
#如:查询"销售部"和"市场部"的所有员工信息
#a.查询"销售部"和"市场部"的部门ID
select id from dept where name = '销售部' or name ='市场部';
#b.根据部门ID,查询员工信息
select * from emp where dept_id in(2,4);
#合并:
select * from emp where dept_id in(select id from dept where name = '销售部' or name ='市场部');
------------------------------------------

#如:查询比 财务部 所有人工资都高的员工信息
#a.查询所有 财务部 人员工资
select id from dept where name='财务部';
select salary from emp where dept_id=(select id from dept where name='财务部');
#b.比 财务部 所有人工作都高的员工信息
select * from emp where salary > all (select salary from emp where dept_id=(select id from dept where name='财务部'));
------------------------------------------

#如:查询比研发部其中任意一人工资高的员工信息
#a.查询研发部所有人 工资
select id from dept where name='研发部';
select salary from emp where dept_id=(select id from dept where name='研发部');
#b.比研发部其中任意一人工资高的员工信息
select * from emp where salary > any (select salary from emp where dept_id=(select id from dept where name='研发部'));

Row subquery:

#子查询返回结果是一行(可以是多列)
#常用的操作符:= , <> , in , not in

#如:查询与"小明"的薪资和直属领导相同的员工信息
#a.查询小明的薪资和直属领导
select salary,managerid from emp where name = '小明';#假设查到 12500  1
#b.查询与小明的薪资和直属领导相同的员工信息
select * from emp where (salary,managerid)=(12500,1);
#合并:
select * from emp where (salary,managerid)=(select salary,managerid from emp where name = '小明');

Table subquery:

#常见的操作符:in
#如:查询与“小明”,“小红”的职位和薪资相同的员工信息
#a.查询“小明","小红"的职位和薪资
select job,salary from emp where name = '小明' or name ='小红';
#b.查询与“小明","小红"的职位和薪资相同的员工信息
select * from emp where (job,salary) in (select job,salary from emp where name = '小明' or name ='小红');
------------------------------------------

#如:查询入职日期在“2006-01-01" 之后 的员工信息,及部门信息
#a.入职日期是"2006-01-01"之后的员工信息
select * from emp where emdate > "2006-01-01";
#b.查询这部分员工,对应的部门信息
select e.*,e.* from (select * from emp where emdate > "2006-01-01") e left join dept d on e.dept_id=d.id
------------------------------------------

#如:查询低于本部门平均工资的员工
#a.查询指定部门平均薪资
select avg(e1.salary) from emp e1 where e1.dept_id=1;
select avg(e1.salary) from emp e1 where e1.dept_id=2;
#b.查询低于本部门平均工资的员工
select * from emp e2.salary where e2.salary < (select avg(e1.salary) from emp e1 where e1.dept_id=e2.dept_id);
#也可以查出平均薪资作为对比
select *,select avg(e1.salary) from emp e1 where e1.dept_id=e2.dept_id '平均' from emp e2.salary where e2.salary < (select avg(e1.salary) from emp e1 where e1.dept_id=e2.dept_id);

11. Transaction operation

#实例如:转账操作(张三给李四转账1000)
#1、查询张三账户余额
select * from account where name = '张三';
#2、将张三账户余额-1000
update account set money = money - 1000 where name ='张三'#3、给李四账余额+1000
update account set money = money + 1000 where name ='李四';
--------------------------------

#事务操作(手动)
#查看/设置事务提交方式
select @@autocomment;#1代表自动提交 0 代表手动提交
set @@autocomment=0;#设置为手动提交
#提交事务
commit;
#回滚事务
rollback;
--------------------------------

#事务操作(自动)
#开启事务
start transactionbegin;
#提交事务
commit;
#回滚事务
rollback;
isolation level dirty read non-repeatable read Phantom reading
read uncommitted have have have
read committed none have have
repeatable read (default) none none have
serializable none none none
#查看事务隔离级别
select @@transaction_isolation;
#设置事务隔离级别
set [session | global] transaction isolation level {
   
   read uncommitted | read committed | repeatable read | serializable}

12. Storage engine

#查看建表语句
show create table 表名;
#查看当前数据库支持的存储引擎
show engines;

Guess you like

Origin blog.csdn.net/m0_46179473/article/details/130752310