更新了部分文档

pull/792/head
jackfrued 2021-06-20 18:05:22 +08:00
parent b67ed793e3
commit 1ef5bf058a
12 changed files with 1085 additions and 602 deletions

View File

@ -4,17 +4,17 @@
1. 数据持久化 - 将数据保存到能够长久保存数据的存储介质中,在掉电的情况下数据也不会丢失。
2. 数据库发展史 - 网状数据库、层次数据库、关系数据库、NoSQL数据库。
2. 数据库发展史 - 网状数据库、层次数据库、关系数据库、NoSQL数据库、NewSQL数据库
> 1970年IBM的研究员E.F.Codd在*Communication of the ACM*上发表了名为*A Relational Model of Data for Large Shared Data Banks*的论文提出了关系模型的概念奠定了关系模型的理论基础。后来Codd又陆续发表多篇文章论述了范式理论和衡量关系系统的12条标准用数学理论奠定了关系数据库的基础。
> 1970年IBM的研究员E.F.Codd在*Communication of the ACM*上发表了名为*A Relational Model of Data for Large Shared Data Banks*的论文,提出了**关系模型**的概念奠定了关系模型的理论基础。后来Codd又陆续发表多篇文章论述了范式理论和衡量关系系统的12条标准用数学理论奠定了关系数据库的基础。
3. 关系数据库特点。
- 理论基础:集合论和关系代数。
- 理论基础:**集合论****关系代数**
- 具体表象:用二维表(有行和列)组织数据。
- 具体表象:用**二维表**(有行和列)组织数据。
- 编程语言结构化查询语言SQL
- 编程语言:**结构化查询语言**SQL
4. ER模型实体关系模型和概念模型图。
@ -181,7 +181,7 @@ MySQL在过去由于性能高、成本低、可靠性好已经成为最流行
再次使用客户端工具连接MySQL服务器时就可以使用新设置的口令了。在实际开发中为了方便用户操作可以选择图形化的客户端工具来连接MySQL服务器包括
- MySQL Workbench官方提供的工具
- Navicat for MySQL界面简单优雅,功能直观强大
- Navicat for MySQL界面简单功能直观
- SQLyog for MySQL强大的MySQL数据库管理员工具
2. 常用命令。
@ -224,81 +224,79 @@ MySQL在过去由于性能高、成本低、可靠性好已经成为最流行
### SQL详解
#### 基本操作
我们通常可以将SQL分为三类DDL数据定义语言、DML数据操作语言和DCL数据控制语言。DDL主要用于创建create、删除drop、修改alter数据库中的对象比如创建、删除和修改二维表DML主要负责插入数据insert、删除数据delete、更新数据update和查询selectDCL通常用于授予权限grant和召回权限revoke
> 说明SQL是不区分大小写的语言为了书写方便下面的SQL都使用了小写字母来书写。
> **说明**SQL是不区分大小写的语言为了书写和识别方便下面的SQL都使用了小写字母来书写。
1. DDL数据定义语言
#### DDL数据定义语言
```SQL
-- 如果存在名为school的数据库就删除它
drop database if exists school;
drop database if exists `school`;
-- 创建名为school的数据库并设置默认的字符集和排序方式
create database school default charset utf8;
create database `school` default character set utf8mb4;
-- 切换到school数据库上下文环境
use school;
use `school`;
-- 创建学院表
create table tb_college
create table `tb_college`
(
collid int auto_increment comment '编号',
collname varchar(50) not null comment '名称',
collintro varchar(500) default '' comment '介绍',
primary key (collid)
);
`col_id` int unsigned auto_increment comment '编号',
`col_name` varchar(50) not null comment '名称',
`col_intro` varchar(5000) default '' comment '介绍',
primary key (`col_id`)
) engine=innodb comment '学院表';
-- 创建学生表
create table tb_student
create table `tb_student`
(
stuid int not null comment '学号',
stuname varchar(20) not null comment '姓名',
stusex boolean default 1 comment '性别',
stubirth date not null comment '出生日期',
stuaddr varchar(255) default '' comment '籍贯',
collid int not null comment '所属学院',
primary key (stuid),
foreign key (collid) references tb_college (collid)
);
`stu_id` int unsigned not null comment '学号',
`stu_name` varchar(20) not null comment '姓名',
`stu_sex` boolean default 1 comment '性别',
`stu_birth` date not null comment '出生日期',
`stu_addr` varchar(255) default '' comment '籍贯',
`col_id` int unsigned not null comment '所属学院',
primary key (`stu_id`),
foreign key (`col_id`) references `tb_college` (`col_id`)
) engine=innodb comment '学生表';
-- 创建教师表
create table tb_teacher
create table `tb_teacher`
(
teaid int not null comment '工号',
teaname varchar(20) not null comment '姓名',
teatitle varchar(10) default '助教' comment '职称',
collid int not null comment '所属学院',
primary key (teaid),
foreign key (collid) references tb_college (collid)
);
`tea_id` int unsigned not null comment '工号',
`tea_name` varchar(20) not null comment '姓名',
`tea_title` varchar(10) default '助教' comment '职称',
`col_id` int unsigned not null comment '所属学院',
primary key (`tea_id`),
foreign key (`col_id`) references `tb_college` (`col_id`)
) engine=innodb comment '老师表';
-- 创建课程表
create table tb_course
create table `tb_course`
(
couid int not null comment '编号',
couname varchar(50) not null comment '名称',
coucredit int not null comment '学分',
teaid int not null comment '授课老师',
primary key (couid),
foreign key (teaid) references tb_teacher (teaid)
);
`cou_id` int unsigned not null comment '编号',
`cou_name` varchar(50) not null comment '名称',
`cou_credit` int unsigned not null comment '学分',
`tea_id` int unsigned not null comment '授课老师',
primary key (`cou_id`),
foreign key (`tea_id`) references `tb_teacher` (`tea_id`)
) engine=innodb comment '课程表';
-- 创建选课记录表
create table tb_record
create table `tb_record`
(
recid int auto_increment comment '选课记录编号',
sid int not null comment '选课学生',
cid int not null comment '所选课程',
seldate datetime default now() comment '选课时间日期',
score decimal(4,1) comment '考试成绩',
primary key (recid),
foreign key (sid) references tb_student (stuid),
foreign key (cid) references tb_course (couid),
unique (sid, cid)
);
`rec_id` bigint unsigned auto_increment comment '选课记录号',
`sid` int unsigned not null comment '学号',
`cid` int unsigned not null comment '课程编号',
`sel_date` date not null comment '选课日期',
`score` decimal(4,1) comment '考试成绩',
primary key (`rec_id`),
foreign key (`sid`) references `tb_student` (`stu_id`),
foreign key (`cid`) references `tb_course` (`cou_id`),
unique (`sid`, `cid`)
) engine=innodb comment '选课记录表';
```
上面的DDL有几个地方需要强调一下
@ -546,18 +544,24 @@ MySQL在过去由于性能高、成本低、可靠性好已经成为最流行
在数据类型的选择上保存字符串数据通常都使用VARCHAR和CHAR两种类型前者通常称为变长字符串而后者通常称为定长字符串对于InnoDB存储引擎行存储格式没有区分固定长度和可变长度列因此VARCHAR类型好CHAR类型没有本质区别后者不一定比前者性能更好。如果要保存的很大字符串可以使用TEXT类型如果要保存很大的字节串可以使用BLOB二进制大对象类型。在MySQL中TEXT和BLOB又分别包括TEXT、MEDIUMTEXT、LONGTEXT和BLOB、MEDIUMBLOB、LONGBLOB三种不同的类型它们主要的区别在于存储数据的最大大小不同。保存浮点数可以用FLOAT或DOUBLE类型而保存定点数应该使用DECIMAL类型。如果要保存时间日期DATETIME类型优于TIMESTAMP类型因为前者能表示的时间日期范围更大。
2. DML
#### DML数据操作语言
```SQL
use school;
-- 插入学院数据
insert into tb_college (collname, collintro) values
insert into `tb_college`
(`col_name`, `col_intro`)
values
('计算机学院', '计算机学院1958年设立计算机专业1981年建立计算机科学系1998年设立计算机学院2005年5月为了进一步整合教学和科研资源学校决定计算机学院和软件学院行政班子合并统一运作、实行教学和学生管理独立运行的模式。 学院下设三个系计算机科学与技术系、物联网工程系、计算金融系两个研究所图象图形研究所、网络空间安全研究院2015年成立三个教学实验中心计算机基础教学实验中心、IBM技术中心和计算机专业实验中心。'),
('外国语学院', '四川大学外国语学院设有7个教学单位6个文理兼收的本科专业拥有1个一级学科博士授予点3个二级学科博士授予点5个一级学科硕士学位授权点5个二级学科硕士学位授权点5个硕士专业授权领域同时还有2个硕士专业学位MTI专业有教职员工210余人其中教授、副教授80余人教师中获得中国国内外名校博士学位和正在职攻读博士学位的教师比例占专任教师的60%以上。'),
('经济管理学院', '四川大学经济学院前身是创办于1905年的四川大学经济科;已故经济学家彭迪先、张与九、蒋学模、胡寄窗、陶大镛、胡代光,以及当代学者刘诗白等曾先后在此任教或学习1905年四川大学设经济科1924年四川大学经济系成立1998年四川大学经济管理学院变更为四川大学经济学院。');
('外国语学院', '外国语学院设有7个教学单位6个文理兼收的本科专业拥有1个一级学科博士授予点3个二级学科博士授予点5个一级学科硕士学位授权点5个二级学科硕士学位授权点5个硕士专业授权领域同时还有2个硕士专业学位MTI专业有教职员工210余人其中教授、副教授80余人教师中获得中国国内外名校博士学位和正在职攻读博士学位的教师比例占专任教师的60%以上。'),
('经济管理学院', '经济学院前身是创办于1905年的经济科已故经济学家彭迪先、张与九、蒋学模、胡寄窗、陶大镛、胡代光以及当代学者刘诗白等曾先后在此任教或学习。');
-- 插入学生数据
insert into tb_student (stuid, stuname, stusex, stubirth, stuaddr, collid) values
(1001, '杨逍', 1, '1990-3-4', '四川成都', 1),
insert into `tb_student`
(`stu_id`, `stu_name`, `stu_sex`, `stu_birth`, `stu_addr`, `col_id`)
values
(1001, '杨过', 1, '1990-3-4', '湖南长沙', 1),
(1002, '任我行', 1, '1992-2-2', '湖南长沙', 1),
(1033, '王语嫣', 0, '1989-12-3', '四川成都', 1),
(1572, '岳不群', 1, '1993-7-19', '陕西咸阳', 1),
@ -566,25 +570,22 @@ MySQL在过去由于性能高、成本低、可靠性好已经成为最流行
(2035, '东方不败', 1, '1988-6-30', null, 2),
(3011, '林震南', 1, '1985-12-12', '福建莆田', 3),
(3755, '项少龙', 1, '1993-1-25', null, 3),
(3923, '杨不悔', 0, '1985-4-17', '四川成都', 3),
(4040, '隔壁老王', 1, '1989-1-1', '四川成都', 2);
-- 删除学生数据
delete from tb_student where stuid=4040;
-- 更新学生数据
update tb_student set stuname='杨过', stuaddr='湖南长沙' where stuid=1001;
(3923, '杨不悔', 0, '1985-4-17', '四川成都', 3);
-- 插入老师数据
insert into tb_teacher (teaid, teaname, teatitle, collid) values
insert into `tb_teacher`
(`tea_id`, `tea_name`, `tea_title`, `col_id`)
values
(1122, '张三丰', '教授', 1),
(1133, '宋远桥', '副教授', 1),
(1144, '杨逍', '副教授', 1),
(2255, '范遥', '副教授', 2),
(3366, '韦一笑', '讲师', 3);
(3366, '韦一笑', default, 3);
-- 插入课程数据
insert into tb_course (couid, couname, coucredit, teaid) values
insert into `tb_course`
(`cou_id`, `cou_name`, `cou_credit`, `tea_id`)
values
(1111, 'Python程序设计', 3, 1122),
(2222, 'Web前端开发', 2, 1122),
(3333, '操作系统', 4, 1122),
@ -596,7 +597,9 @@ MySQL在过去由于性能高、成本低、可靠性好已经成为最流行
(9999, '审计学', 3, 3366);
-- 插入选课数据
insert into tb_record (sid, cid, seldate, score) values
insert into `tb_record`
(`sid`, `cid`, `sel_date`, `score`)
values
(1001, 1111, '2017-09-01', 95),
(1001, 2222, '2017-09-01', 87.5),
(1001, 3333, '2017-09-01', 100),
@ -611,66 +614,131 @@ MySQL在过去由于性能高、成本低、可靠性好已经成为最流行
(1378, 1111, '2017-09-05', 82),
(1378, 7777, '2017-09-02', 65.5),
(2035, 7777, '2018-09-03', 88),
(2035, 9999, default, null),
(3755, 1111, default, null),
(3755, 8888, default, null),
(2035, 9999, '2019-09-02', null),
(3755, 1111, '2019-09-02', null),
(3755, 8888, '2019-09-02', null),
(3755, 9999, '2017-09-01', 92);
```
#### DQL数据查询语言
```SQL
-- 查询所有学生信息
-- 查询所有学生的所有信息
select * from tb_student;
select stu_id, stu_name, stu_sex, stu_birth, stu_addr, col_id from tb_student;
-- 查询所有课程名称及学分(投影和别名)
select couname, coucredit from tb_course;
select couname as 课程名称, coucredit as 学分 from tb_course;
-- 查询所有学生的姓名和性别(条件运算)
select stuname as 姓名, case stusex when 1 then '男' else '女' end as 性别 from tb_student;
select stuname as 姓名, if(stusex, '男', '女') as 性别 from tb_student;
select cou_name as 课程名称, cou_credit as 学分 from tb_course;
-- 查询所有女学生的姓名和出生日期(筛选)
select stuname, stubirth from tb_student where stusex=0;
select stu_name, stu_birth from tb_student where stu_sex=0;
-- 查询所有80后学生的姓名、性别和出生日期(筛选)
select stuname, stusex, stubirth from tb_student where stubirth>='1980-1-1' and stubirth<='1989-12-31';
select stuname, stusex, stubirth from tb_student where stubirth between '1980-1-1' and '1989-12-31';
select stu_name, stu_sex, stu_birth from tb_student
where stu_birth>='1980-1-1' and stu_birth<='1989-12-31';
-- 查询姓"杨"的学生姓名和性别(模糊)
select stuname, stusex from tb_student where stuname like '杨%';
select stu_name, stu_sex, stu_birth from tb_student
where stu_birth between '1980-1-1' and '1989-12-31';
-- 查询姓"杨"名字两个字的学生姓名和性别(模糊)
select stuname, stusex from tb_student where stuname like '杨_';
-- 补充1在查询时可以对列的值进行处理
select
stu_name as 姓名,
case stu_sex when 1 then '男' else '女' end as 性别,
stu_birth as 生日
from tb_student
where stu_birth between '1980-1-1' and '1989-12-31';
-- 查询姓"杨"名字三个字的学生姓名和性别(模糊)
select stuname, stusex from tb_student where stuname like '杨__';
-- 补充2MySQL方言(使用数据库特有的函数)
-- 例如Oracle中做同样事情的函数叫做decode
select
stu_name as 姓名,
if(stu_sex, '男', '女') as 性别,
stu_birth as 生日
from tb_student
where stu_birth between '1980-1-1' and '1989-12-31';
-- 查询名字中有"不"字或"嫣"字的学生的姓名(模糊)
select stuname, stusex from tb_student where stuname like '%不%' or stuname like '%嫣%';
-- 查询所有80后女学生的姓名和出生日期
select stu_name, stu_birth from tb_student
where stu_birth between '1980-1-1' and '1989-12-31' and stu_sex=0;
-- 查询所有的80后学生或女学生的姓名和出生日期
select stu_name, stu_birth from tb_student
where stu_birth between '1980-1-1' and '1989-12-31' or stu_sex=0;
-- 查询姓“杨”的学生姓名和性别(模糊)
-- 在SQL中通配符%可以匹配零个或任意多个字符
select stu_name, stu_sex from tb_student where stu_name like '杨%';
-- 查询姓“杨”名字两个字的学生姓名和性别(模糊)
-- 在SQL中通配符_可以刚刚好匹配一个字符
select stu_name, stu_sex from tb_student where stu_name like '杨_';
-- 查询姓“杨”名字三个字的学生姓名和性别(模糊)
select stu_name, stu_sex from tb_student where stu_name like '杨__';
-- 查询名字中有“不”字或“嫣”字的学生的姓名(模糊)
-- 提示:前面带%的模糊查询性能基本上都是非常糟糕的
select stu_name from tb_student
where stu_name like '%不%' or stu_name like '%嫣%';
update tb_student set stu_name='岳不嫣' where stu_id=1572;
-- 并集运算
select stu_name from tb_student where stu_name like '%不%'
union
select stu_name from tb_student where stu_name like '%嫣%';
select stu_name from tb_student where stu_name like '%不%'
union all
select stu_name from tb_student where stu_name like '%嫣%';
-- 正则表达式模糊查询
select stu_name, stu_sex from tb_student where stu_name regexp '^杨.{2}$';
-- 查询没有录入家庭住址的学生姓名(空值)
select stuname from tb_student where stuaddr is null;
-- null作任何运算结果也是产生nullnull相当于是条件不成立
select stu_name from tb_student where stu_addr is null;
select stu_name from tb_student where stu_addr<=>null;
-- 查询录入了家庭住址的学生姓名(空值)
select stuname from tb_student where stuaddr is not null;
select stu_name from tb_student where stu_addr is not null;
-- 查询学生选课的所有日期(去重)
select distinct seldate from tb_record;
select distinct sel_date from tb_record;
-- 查询学生的家庭住址(去重)
select distinct stuaddr from tb_student where stuaddr is not null;
select distinct stu_addr from tb_student where stu_addr is not null;
-- 查询男学生的姓名和生日按年龄从大到小排列(排序)
select stuname as 姓名, datediff(curdate(), stubirth) div 365 as 年龄 from tb_student where stusex=1 order by 年龄 desc;
-- asc - 升序从小到大desc - 降序(从大到小)
select stu_name, stu_birth from tb_student
where stu_sex=1 order by stu_birth asc;
-- 查询年龄最大的学生的出生日期(聚合函数)
select min(stubirth) from tb_student;
select stu_name, stu_birth from tb_student
where stu_sex=1 order by stu_birth desc;
-- 查询年龄最大的学生的出生日期(聚合函数) ---> 找出最小的生日
select min(stu_birth) from tb_student;
select
min(stu_birth) as 生日,
floor(datediff(curdate(), min(stu_birth))/365) as 年龄
from tb_student;
-- 查询年龄最小的学生的出生日期(聚合函数)
select max(stubirth) from tb_student;
select
max(stu_birth) as 生日,
floor(datediff(curdate(), max(stu_birth))/365) as 年龄
from tb_student;
-- 查询男女学生的人数(分组和聚合函数)
select stusex, count(*) from tb_student group by stusex;
-- 查询所有考试的平均成绩
-- 聚合函数在遇到null值会做忽略的处理
-- 如果做计数操作建议使用count(*),这样才不会漏掉空值
select avg(score) from tb_record;
select sum(score) / count(score) from tb_record;
select sum(score) / count(*) from tb_record;
-- 查询课程编号为1111的课程的平均成绩(筛选和聚合函数)
select avg(score) from tb_record where cid=1111;
@ -678,37 +746,87 @@ MySQL在过去由于性能高、成本低、可靠性好已经成为最流行
-- 查询学号为1001的学生所有课程的平均分(筛选和聚合函数)
select avg(score) from tb_record where sid=1001;
select count(distinct stu_addr) from tb_student where stu_addr is not null;
-- 查询男女学生的人数(分组和聚合函数)
-- SACSplit - Aggregate - Combine
select
if(stu_sex, '男', '女') as 性别,
count(*) as 人数
from tb_student group by stu_sex;
-- 统计每个学院男女学生的人数
select
col_id as 学院,
if(stu_sex, '男', '女') as 性别,
count(*) as 人数
from tb_student group by col_id, stu_sex;
-- 查询每个学生的学号和平均成绩(分组和聚合函数)
select sid as 学号, avg(score) as 平均分 from tb_record group by sid;
select
sid as 学号,
round(avg(score),1) as 平均分
from tb_record group by sid;
-- 查询平均成绩大于等于90分的学生的学号和平均成绩
-- 分组以前的筛选使用where子句 / 分组以后的筛选使用having子句
select sid as 学号, avg(score) as 平均分 from tb_record group by sid having 平均分>=90;
-- 分组以前的数据筛选使用where子句分组以后的数据筛选使用having子句
select
sid as 学号,
round(avg(score),1) as 平均分
from tb_record
group by sid having 平均分>=90;
-- 查询年龄最大的学生的姓名(子查询/嵌套的查询)
select stuname from tb_student where stubirth=( select min(stubirth) from tb_student );
-- 查询年龄最大的学生的姓名(子查询)
-- 嵌套查询:把一个查询的结果作为另外一个查询的一部分来使用。
select stu_name from tb_student where stu_birth=(
select min(stu_birth) from tb_student
);
-- 查询年龄最大的学生姓名和年龄(子查询+运算)
select stuname as 姓名, datediff(curdate(), stubirth) div 365 as 年龄 from tb_student where stubirth=( select min(stubirth) from tb_student );
select
stu_name as 姓名,
floor(datediff(curdate(), stu_birth) / 365) as 年龄
from tb_student where stu_birth=(
select min(stu_birth) from tb_student
);
-- 查询选了两门以上的课程的学生姓名(子查询/分组条件/集合运算)
select stuname from tb_student where stuid in ( select stuid from tb_record group by stuid having count(stuid)>2 );
select stu_name from tb_student where stu_id in (
select sid from tb_record group by sid having count(*)>2
);
-- 查询课程的名称、学分和授课老师的姓名(连接查询)
select cou_name, cou_credit, tea_name
from tb_course, tb_teacher
where tb_course.tea_id=tb_teacher.tea_id;
select cou_name, cou_credit, tea_name from tb_course t1
inner join tb_teacher t2 on t1.tea_id=t2.tea_id;
-- 查询学生姓名、课程名称以及成绩(连接查询)
select stuname, couname, score from tb_student t1, tb_course t2, tb_record t3 where stuid=sid and couid=cid and score is not null;
select stu_name, cou_name, score
from tb_record, tb_student, tb_course
where stu_id=sid and cou_id=cid and score is not null;
-- 查询学生姓名、课程名称以及成绩按成绩从高到低查询第11-15条记录(内连接+分页)
select stuname, couname, score from tb_student inner join tb_record on stuid=sid inner join tb_course on couid=cid where score is not null order by score desc limit 5 offset 10;
select stuname, couname, score from tb_student inner join tb_record on stuid=sid inner join tb_course on couid=cid where score is not null order by score desc limit 10, 5;
select stu_name, cou_name, score from tb_student
inner join tb_record on stu_id=sid
inner join tb_course on cou_id=cid
where score is not null;
-- 查询选课学生的姓名和平均成绩(子查询和连接查询)
select stuname, avgmark from tb_student, ( select sid, avg(score) as avgmark from tb_record group by sid ) temp where stuid=sid;
select stuname, avgmark from tb_student inner join ( select sid, avg(score) as avgmark from tb_record group by sid ) temp on stuid=sid;
select stu_name, avg_score
from tb_student, (select sid, round(avg(score),1) as avg_score
from tb_record group by sid
) tb_temp where stu_id=sid;
-- 查询每个学生的姓名和选课数量(左外连接和子查询)
select stuname, ifnull(total, 0) from tb_student left outer join ( select sid, count(sid) as total from tb_record group by sid ) temp on stuid=sid;
select
stu_name as 姓名,
ifnull(total, 0) as 选课数量
from tb_student left outer join (
select sid, count(*) as total from tb_record group by sid
) tb_temp on stu_id=sid;
```
上面的DML有几个地方需要加以说明
@ -784,7 +902,7 @@ MySQL在过去由于性能高、成本低、可靠性好已经成为最流行
| LAST_INSERT_ID | 返回最后一个自增主键的值 |
| UUID / UUID_SHORT | 返回全局唯一标识符 |
3. DCL
#### DCL数据控制语言
```SQL
-- 创建可以远程登录的root账号并为其指定口令
@ -805,7 +923,7 @@ MySQL在过去由于性能高、成本低、可靠性好已经成为最流行
> 说明:创建一个可以允许任意主机登录并且具有超级管理员权限的用户在现实中并不是一个明智的决定,因为一旦该账号的口令泄露或者被破解,数据库将会面临灾难级的风险。
#### 索引
### 索引
索引是关系型数据库中用来提升查询性能最为重要的手段。关系型数据库中的索引就像一本书的目录,我们可以想象一下,如果要从一本书中找出某个知识点,但是这本书没有目录,这将是意见多么可怕的事情(我们估计得一篇一篇的翻下去,才能确定这个知识点到底在什么位置)。创建索引虽然会带来存储空间上的开销,就像一本书的目录会占用一部分的篇幅一样,但是在牺牲空间后换来的查询时间的减少也是非常显著的。
@ -836,10 +954,25 @@ possible_keys: NULL
在上面的SQL执行计划中有几项值得我们关注
1. `type`MySQL在表中找到满足条件的行的方式也称为访问类型包括ALL全表扫描、index索引全扫描、range索引范围扫描、ref非唯一索引扫描、eq_ref唯一索引扫描、const/system、NULL。在所有的访问类型中很显然ALL是性能最差的它代表了全表扫描是指要扫描表中的每一行才能找到匹配的行。
2. possible_keysMySQL可以选择的索引但是**有可能不会使用**。
3. keyMySQL真正使用的索引。
4. rows执行查询需要扫描的行数这是一个**预估值**。
1. `select_type`:查询的类型。
- SIMPLE简单SELECT不需要使用UNION操作或子查询。
- PRIMARY如果查询包含子查询最外层的SELECT被标记为PRIMARY。
- UNIONUNION操作中第二个或后面的SELECT语句。
- SUBQUERY子查询中的第一个SELECT。
- DERIVED派生表的SELECT子查询。
2. `table`:查询对应的表。
3. `type`MySQL在表中找到满足条件的行的方式也称为访问类型包括ALL全表扫描、index索引全扫描只遍历索引树、range索引范围扫描、ref非唯一索引扫描、eq_ref唯一索引扫描、const/system常量级查询、NULL不需要访问表或索引。在所有的访问类型中很显然ALL是性能最差的它代表的全表扫描是指要扫描表中的每一行才能找到匹配的行。
4. `possible_keys`MySQL可以选择的索引但是**有可能不会使用**。
5. `key`MySQL真正使用的索引如果为NULL就表示没有使用索引。
6. `key_len`:使用的索引的长度,在不影响查询的情况下肯定是长度越短越好。
7. `rows`:执行查询需要扫描的行数,这是一个**预估值**。
8. `extra`:关于查询额外的信息。
- `Using filesort`MySQL无法利用索引完成排序操作。
- `Using index`:只使用索引的信息而不需要进一步查表来获取更多的信息。
- `Using temporary`MySQL需要使用临时表来存储结果集常用于分组和排序。
- `Impossible where``where`子句会导致没有符合条件的行。
- `Distinct`MySQL发现第一个匹配行后停止为当前的行组合搜索更多的行。
- `Using where`:查询的列未被索引覆盖,筛选条件并不是索引的前导列。
从上面的执行计划可以看出,当我们通过学生名字查询学生时实际上是进行了全表扫描,不言而喻这个查询性能肯定是非常糟糕的,尤其是在表中的行很多的时候。如果我们需要经常通过学生姓名来查询学生,那么就应该在学生姓名对应的列上创建索引,通过索引来加速查询。
@ -924,7 +1057,7 @@ drop index idx_student_name on tb_student;
最后还有一点需要说明InnoDB使用的B-tree索引数值类型的列除了等值判断时索引会生效之外使用>、<、>=、<=、BETWEEN...AND... 、<>时,索引仍然生效;对于字符串类型的列,如果使用不以通配符开头的模糊查询,索引也是起作用的,但是其他的情况会导致索引失效,这就意味着很有可能会做全表查询。
#### 视图
### 视图
视图是关系型数据库中将一组查询指令构成的结果集组合成可查询的数据表的对象。简单的说视图就是虚拟的表但与数据表不同的是数据表是一种实体结构而视图是一种虚拟结构你也可以将视图理解为保存在数据库中被赋予名字的SQL语句。
@ -993,18 +1126,18 @@ drop view vw_student_score;
2. 创建视图时可以使用`order by`子句,但如果从视图中检索数据时也使用了`order by`,那么该视图中原先的`order by`会被覆盖。
3. 视图无法使用索引,也不会激发触发器(实际开发中因为性能等各方面的考虑,通常不建议使用触发器,所以我们也不对这个概念进行介绍)的执行。
#### 存储过程
### 过程
存储过程是事先编译好存储在数据库中的一组SQL的集合调用存储过程可以简化应用程序开发人员的工作减少与数据库服务器之间的通信对于提升数据操作的性能也是有帮助的。其实迄今为止我们使用的SQL语句都是针对一个或多个表的单条语句但在实际开发中经常会遇到某个操作需要多条SQL语句才能完成的情况。例如电商网站在受理用户订单时需要做以下一系列的处理。
过程(又称存储过程是事先编译好存储在数据库中的一组SQL的集合调用过程可以简化应用程序开发人员的工作减少与数据库服务器之间的通信对于提升数据操作的性能也是有帮助的。其实迄今为止我们使用的SQL语句都是针对一个或多个表的单条语句但在实际开发中经常会遇到某个操作需要多条SQL语句才能完成的情况。例如电商网站在受理用户订单时需要做以下一系列的处理。
1. 通过查询来核对库存中是否有对应的物品以及库存是否充足。
2. 如果库存有物品,需要锁定库存以确保这些物品不再卖给别人, 并且要减少可用的物品数量以反映正确的库存量。
3. 如果库存不足,可能需要进一步与供应商进行交互或者至少产生一条系统提示消息。
4. 不管受理订单是否成功,都需要产生流水记录,而且需要给对应的用户产生一条通知信息。
我们可以通过存储过程将复杂的操作封装起来,这样不仅有助于保证数据的一致性,而且将来如果业务发生了变动,只需要调整和修改存储过程即可。对于调用存储过程的用户来说,存储过程并没有暴露数据表的细节,而且执行存储过程比一条条的执行一组SQL要快得多。
我们可以通过过程将复杂的操作封装起来这样不仅有助于保证数据的一致性而且将来如果业务发生了变动只需要调整和修改过程即可。对于调用过程的用户来说过程并没有暴露数据表的细节而且执行过程比一条条的执行一组SQL要快得多。
下面的存储过程实现了查询某门课程的最高分、最低分和平均分。
下面的过程实现了查询某门课程的最高分、最低分和平均分。
```SQL
drop procedure if exists sp_score_by_cid;
@ -1032,11 +1165,11 @@ call sp_score_by_cid(1111, @a, @b, @c);
select @a, @b, @c;
```
> 说明:在定义存储过程时因为可能需要书写多条SQL而分隔这些SQL需要使用分号作为分隔符如果这个时候仍然用分号表示整段代码结束那么定义存储过程的SQL就会出现错误所以上面我们用`delimiter $$`将整段代码结束的标记定义为`$$`,那么代码中的分号将不再表示整段代码的结束,需要马上执行,整段代码在遇到`end $$`时才输入完成并执行。在定义完存储过程后,通过`delimiter ;`将结束符重新改回成分号。
> **说明**在定义过程时因为可能需要书写多条SQL而分隔这些SQL需要使用分号作为分隔符如果这个时候仍然用分号表示整段代码结束那么定义过程的SQL就会出现错误所以上面我们用`delimiter $$`将整段代码结束的标记定义为`$$`,那么代码中的分号将不再表示整段代码的结束,整段代码只会在遇到`end $$`时才会执行。在定义完过程后,通过`delimiter ;`将结束符重新改回成分号(恢复现场)
上面定义的存储过程有四个参数,其中第一个参数是输入参数,代表课程的编号,后面的参数都是输出参数,因为存储过程不能定义返回值,只能通过输出参数将执行结果带出,定义输出参数的关键字是`out`,默认情况下参数都是输入参数。
上面定义的过程有四个参数,其中第一个参数是输入参数,代表课程的编号,后面的参数都是输出参数,因为过程不能定义返回值,只能通过输出参数将执行结果带出,定义输出参数的关键字是`out`,默认情况下参数都是输入参数。
调用存储过程。
调用过程。
```SQL
call sp_score_by_cid(1111, @a, @b, @c);
@ -1048,17 +1181,36 @@ call sp_score_by_cid(1111, @a, @b, @c);
select @a as 最高分, @b as 最低分, @c as 平均分;
```
删除存储过程。
删除过程。
```SQL
drop procedure sp_score_by_cid;
```
存储过程中,我们可以定义变量、条件,可以使用分支和循环语句,可以通过游标操作查询结果,还可以使用事件调度器,这些内容我们暂时不在此处进行介绍。虽然我们说了很多存储过程的好处,但是在实际开发中,如果过度的使用存储过程,将大量复杂的运算放到存储过程中,也会导致占用数据库服务器的CPU资源造成数据库服务器承受巨大的压力。为此我们一般会将复杂的运算和处理交给应用服务器因为很容易部署多台应用服务器来分摊这些压力。
在过程中,我们可以定义变量、条件,可以使用分支和循环语句,可以通过游标操作查询结果,还可以使用事件调度器,这些内容我们暂时不在此处进行介绍。虽然我们说了很多过程的好处,但是在实际开发中,如果过度的使用过程并将大量复杂的运算放到过程中,必然会导致占用数据库服务器的CPU资源造成数据库服务器承受巨大的压力。为此我们一般会将复杂的运算和处理交给应用服务器因为很容易部署多台应用服务器来分摊这些压力。
### 几个重要的概念
### MySQL8窗口函数
#### 范式理论 - 设计二维表的指导思想
MySQL从8.0开始支持窗口函数大多数商业数据库和一些开源数据库早已提供了对窗口函数的支持有的也将其称之为OLAP联机分析和处理函数听名字就知道跟统计和分析相关。为了帮助大家理解窗口函数我们先说说窗口的概念。
窗口可以理解为记录的集合,窗口函数也就是在满足某种条件的记录集合上执行的特殊函数,对于每条记录都要在此窗口内执行函数。窗口函数和我们上面讲到的聚合函数比较容易混淆,二者的区别主要在于聚合函数是将多条记录聚合为一条记录,窗口函数是每条记录都会执行,执行后记录条数不会变。窗口函数不仅仅是几个函数,它是一套完整的语法,函数只是该语法的一部分,基本语法如下所示:
```SQL
<窗口函数> over (partition by <用于分组的列名> order by <用户排序的列名>)
```
上面语法中,窗口函数的位置可以放以下两种函数:
1. 专用窗口函数,包括:`rank`、`dense_rank`和`row_number`等。
2. 聚合函数,包括:`sum`、`avg`、`max`、`min`和`count`等。
> **参考链接**<https://zhuanlan.zhihu.com/p/92654574>
### 其他内容
#### 范式理论
范式理论是设计关系型数据库中二维表的指导思想。
1. 第一范式:数据表的每个列的值域都是由原子值组成的,不能够再分割。
2. 第二范式:数据表里的所有数据都要和该数据表的键(主键与候选键)有完全依赖关系。
@ -1119,9 +1271,7 @@ drop procedure sp_score_by_cid;
rollback
```
### 其他内容
大家应该能够想到关于MySQL的知识肯定远远不止上面列出的这些比如MySQL的性能优化、管理和维护MySQL的相关工具、MySQL数据的备份和恢复、监控MySQL、部署高可用架构等问题我们在这里都没有进行讨论。当然这些内容也都是跟项目开发密切相关的我们就留到后续的章节中再续点进行讲解。
大家应该能够想到关于MySQL的知识肯定远远不止上面列出的这些比如MySQL的性能优化、管理和维护MySQL的相关工具、MySQL数据的备份和恢复、监控MySQL、部署高可用架构等问题我们在这里都没有进行讨论。当然这些内容也都是跟项目开发密切相关的我们就留到有需要的时候再进行讲解。
### Python数据库编程
@ -1354,3 +1504,4 @@ insert into tb_emp values
if __name__ == '__main__':
main()
```

View File

@ -25,14 +25,13 @@ job varchar(20) not null comment '员工职位',
mgr int comment '主管编号',
sal int not null comment '员工月薪',
comm int comment '每月补贴',
dno int comment '所在部门编号',
primary key (eno),
foreign key (dno) references tb_dept(dno),
foreign key (mgr) references tb_emp(eno)
dno int comment '所在部门编号'
);
alter table tb_emp add constraint pk_emp_eno primary key (eno);
alter table tb_emp add constraint uk_emp_ename unique (ename);
-- alter table tb_emp add constraint fk_emp_mgr foreign key (mgr) references tb_emp (eno);
-- alter table tb_emp add constraint fk_emp_dno foreign key (dno) references tb_dept (dno);
alter table tb_emp add constraint fk_emp_dno foreign key (dno) references tb_dept (dno);
insert into tb_emp values
(7800, '张三丰', '总裁', null, 9000, 1200, 20),
@ -61,11 +60,11 @@ insert into tb_emp values
-- 查询月薪最高的员工(Boss除外)的姓名和月薪
-- 查询超过平均薪的员工的姓名和月薪
-- 查询薪超过平均薪的员工的姓名和月薪
-- 查询超过其所在部门平均薪的员工的姓名、部门编号和月薪
-- 查询薪超过其所在部门平均薪的员工的姓名、部门编号和月薪
-- 查询部门中最高的人姓名、月薪和所在部门名称
-- 查询部门中薪最高的人姓名、月薪和所在部门名称
-- 查询主管的姓名和职位

View File

@ -14,7 +14,7 @@ create table `tb_college`
`col_name` varchar(50) not null comment '名称',
`col_intro` varchar(5000) default '' comment '介绍',
primary key (`col_id`)
) engine=innodb;
) engine=innodb comment '学院表';
-- 创建学生表
create table `tb_student`
@ -27,7 +27,7 @@ create table `tb_student`
`col_id` int unsigned not null comment '所属学院',
primary key (`stu_id`),
foreign key (`col_id`) references `tb_college` (`col_id`)
) engine=innodb;
) engine=innodb comment '学生表';
-- 创建教师表
create table `tb_teacher`
@ -38,7 +38,7 @@ create table `tb_teacher`
`col_id` int unsigned not null comment '所属学院',
primary key (`tea_id`),
foreign key (`col_id`) references `tb_college` (`col_id`)
);
) engine=innodb comment '老师表';
-- 创建课程表
create table `tb_course`
@ -49,7 +49,7 @@ create table `tb_course`
`tea_id` int unsigned not null comment '授课老师',
primary key (`cou_id`),
foreign key (`tea_id`) references `tb_teacher` (`tea_id`)
);
) engine=innodb comment '课程表';
-- 创建选课记录表
create table `tb_record`
@ -63,7 +63,7 @@ primary key (`rec_id`),
foreign key (`sid`) references `tb_student` (`stu_id`),
foreign key (`cid`) references `tb_course` (`cou_id`),
unique (`sid`, `cid`)
);
) engine=innodb comment '选课记录表';
-- 插入学院数据
insert into `tb_college`

View File

@ -0,0 +1,144 @@
drop database if exists hrs;
create database hrs default charset utf8mb4;
use hrs;
create table tb_dept
(
dno int not null comment '编号',
dname varchar(10) not null comment '名称',
dloc varchar(20) not null comment '所在地',
primary key (dno)
);
insert into tb_dept values
(10, '会计部', '北京'),
(20, '研发部', '成都'),
(30, '销售部', '重庆'),
(40, '运维部', '深圳');
create table tb_emp
(
eno int not null comment '员工编号',
ename varchar(20) not null comment '员工姓名',
job varchar(20) not null comment '员工职位',
mgr int comment '主管编号',
sal int not null comment '员工月薪',
comm int comment '每月补贴',
dno int comment '所在部门编号',
primary key (eno),
foreign key (dno) references tb_dept (dno)
);
-- alter table tb_emp add constraint pk_emp_eno primary key (eno);
-- alter table tb_emp add constraint uk_emp_ename unique (ename);
-- alter table tb_emp add constraint fk_emp_mgr foreign key (mgr) references tb_emp (eno);
-- alter table tb_emp add constraint fk_emp_dno foreign key (dno) references tb_dept (dno);
insert into tb_emp values
(7800, '张三丰', '总裁', null, 9000, 1200, 20),
(2056, '乔峰', '分析师', 7800, 5000, 1500, 20),
(3088, '李莫愁', '设计师', 2056, 3500, 800, 20),
(3211, '张无忌', '程序员', 2056, 3200, null, 20),
(3233, '丘处机', '程序员', 2056, 3400, null, 20),
(3251, '张翠山', '程序员', 2056, 4000, null, 20),
(5566, '宋远桥', '会计师', 7800, 4000, 1000, 10),
(5234, '郭靖', '出纳', 5566, 2000, null, 10),
(3344, '黄蓉', '销售主管', 7800, 3000, 800, 30),
(1359, '胡一刀', '销售员', 3344, 1800, 200, 30),
(4466, '苗人凤', '销售员', 3344, 2500, null, 30),
(3244, '欧阳锋', '程序员', 3088, 3200, null, 20),
(3577, '杨过', '会计', 5566, 2200, null, 10),
(3588, '朱九真', '会计', 5566, 2500, null, 10);
-- 查询月薪最高的员工姓名和月薪
select ename, sal from tb_emp where sal=(select max(sal) from tb_emp);
select ename, sal from tb_emp where sal>=all(select sal from tb_emp);
-- 查询员工的姓名和年薪((月薪+补贴)*13)
select ename, (sal+ifnull(comm,0))*13 as ann_sal from tb_emp order by ann_sal desc;
-- 查询有员工的部门的编号和人数
select dno, count(*) as total from tb_emp group by dno;
-- 查询所有部门的名称和人数
select dname, ifnull(total,0) as total from tb_dept left join
(select dno, count(*) as total from tb_emp group by dno) tb_temp
on tb_dept.dno=tb_temp.dno;
-- 查询月薪最高的员工(Boss除外)的姓名和月薪
select ename, sal from tb_emp where sal=(
select max(sal) from tb_emp where mgr is not null
);
-- 查询月薪排第2名的员工的姓名和月薪
select ename, sal from tb_emp where sal=(
select distinct sal from tb_emp order by sal desc limit 1,1
);
select ename, sal from tb_emp where sal=(
select max(sal) from tb_emp where sal<(select max(sal) from tb_emp)
);
-- 查询月薪超过平均月薪的员工的姓名和月薪
select ename, sal from tb_emp where sal>(select avg(sal) from tb_emp);
-- 查询月薪超过其所在部门平均月薪的员工的姓名、部门编号和月薪
select ename, t1.dno, sal from tb_emp t1 inner join
(select dno, avg(sal) as avg_sal from tb_emp group by dno) t2
on t1.dno=t2.dno and sal>avg_sal;
-- 查询部门中月薪最高的人姓名、月薪和所在部门名称
select ename, sal, dname
from tb_emp t1, tb_dept t2, (
select dno, max(sal) as max_sal from tb_emp group by dno
) t3 where t1.dno=t2.dno and t1.dno=t3.dno and sal=max_sal;
-- 查询主管的姓名和职位
-- 提示尽量少用in/not in运算尽量少用distinct操作
-- 可以使用存在性判断exists/not exists替代集合运算和去重操作
select ename, job from tb_emp where eno in (
select distinct mgr from tb_emp where mgr is not null
);
select ename, job from tb_emp where eno=any(
select distinct mgr from tb_emp where mgr is not null
);
select ename, job from tb_emp t1 where exists (
select 'x' from tb_emp t2 where t1.eno=t2.mgr
);
-- MySQL8有窗口函数row_number() / rank() / dense_rank()
-- 查询月薪排名4~6名的员工的排名、姓名和月薪
select ename, sal from tb_emp order by sal desc limit 3,3;
select row_num, ename, sal from
(select @a:=@a+1 as row_num, ename, sal
from tb_emp, (select @a:=0) t1 order by sal desc) t2
where row_num between 4 and 6;
-- 窗口函数不适合业务数据库,只适合做离线数据分析
select
ename, sal,
row_number() over (order by sal desc) as row_num,
rank() over (order by sal desc) as ranking,
dense_rank() over (order by sal desc) as dense_ranking
from tb_emp limit 3 offset 3;
select ename, sal, ranking from (
select ename, sal, dense_rank() over (order by sal desc) as ranking from tb_emp
) tb_temp where ranking between 4 and 6;
-- 窗口函数主要用于解决TopN查询问题
-- 查询每个部门月薪排前2名的员工姓名、月薪和部门编号
select ename, sal, dno from (
select ename, sal, dno, rank() over (partition by dno order by sal desc) as ranking
from tb_emp
) tb_temp where ranking<=2;
select ename, sal, dno from tb_emp t1
where (select count(*) from tb_emp t2 where t1.dno=t2.dno and t2.sal>t1.sal)<2
order by dno asc, sal desc;

File diff suppressed because one or more lines are too long

View File

@ -1,22 +0,0 @@
drop database if exists shop;
create database shop default charset utf8;
use shop;
drop table if exists tb_goods;
create table tb_goods
(
gid int not null auto_increment,
gname varchar(50) not null,
gprice decimal(10,2) not null,
gimage varchar(255),
primary key (gid)
);
insert into tb_goods values
(default, '乐事Lays无限薯片', 8.2, 'images/lay.jpg'),
(default, '旺旺 仙贝 加量装 540g', 18.5, 'images/wang.jpg'),
(default, '多儿比Dolbee黄桃水果罐头', 6.8, 'images/dolbee.jpg'),
(default, '王致和 精制料酒 500ml', 7.9, 'images/wine.jpg'),
(default, '陈克明 面条 鸡蛋龙须挂面', 1.0, 'images/noodle.jpg'),
(default, '鲁花 菜籽油 4L', 69.9, 'images/oil.jpg');

File diff suppressed because one or more lines are too long

View File

@ -259,7 +259,7 @@ Notebook是基于网页的用于交互计算的应用程序可以用于代码
在实际工作中,我们经常通过四分位数再配合[箱线图](https://zhuanlan.zhihu.com/p/110580568)来发现异常值。例如,小于$Q_1 - 1.5 \times IQR$的值或大于$Q3 + 1.5 \times IQR$的值可以视为普通异常值,而小于$Q_1 - 3 \times IQR$的值或大于$Q3 + 3 \times IQR$的值通常视为极度异常值。这种检测异常值的方法跟[“3西格玛法则”](https://zh.wikipedia.org/wiki/68%E2%80%9395%E2%80%9399.7%E5%8E%9F%E5%89%87)的道理是一致的,如下图所示。
![](res/quartile_and_3sigma.png)
![](res/3sigma.png)
2. 离散趋势

View File

Before

Width:  |  Height:  |  Size: 51 KiB

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

View File

@ -0,0 +1,149 @@
## 概率基础
### 数据的集中趋势
我们经常会使用以下几个指标来描述一组数据的集中趋势:
1. 均值 - 均值代表某个数据集的整体水平,我们经常提到的客单价、平均访问时长、平均配送时长等指标都是均值。均值的缺点是容易受极值的影响,虽然可以使用加权平均值来消除极值的影响,但是可能事先并不清楚数据的权重;对于正数可以用几何平均值来替代算术平均值。
- 算术平均值:$$\bar{x}=\frac{\sum_{i=1}^{n}x_{i}}{n}=\frac{x_{1}+x_{2}+\cdots +x_{n}}{n}$$。
- 几何平均值:$$\left(\prod_{i=1}^{n}x_{i}\right)^{\frac{1}{n}}={\sqrt[{n}]{x_{1}x_{2} \cdots x_{n}}}$$。
2. 中位数 - 将数据按照升序或降序排列后位于中间的数,它描述了数据的中等水平。
3. 众数 - 数据集合中出现频次最多的数据,它代表了数据的一般水平。数据的趋势越集中,众数的代表性就越好。众数不受极值的影响,但是无法保证唯一性和存在性。
例子有A和B两组数据。
```
A组5, 6, 6, 6, 6, 8, 10
B组3, 5, 5, 6, 6, 9, 12
```
A组
均值6.74中位数6众数6。
B组
均值6.57中位数6众数5, 6。
对A组的数据进行一些调整。
```
A组5, 6, 6, 6, 6, 8, 10, 20
B组3, 5, 5, 6, 6, 9, 12
```
A组的均值会大幅度提升但中位数和众数却没有变化。
> **思考**怎样判断上面的20到底是不是一个异常值
| | 优点 | 缺点 |
| ------ | -------------------------------- | ------------------------------------ |
| 均值 | 充分利用了所有数据,适应性强 | 容易收到极端值(异常值)的影响 |
| 中位数 | 能够避免被极端值(异常值)的影响 | 不敏感 |
| 众数 | 能够很好的反映数据的集中趋势 | 有可能不存在(数据没有明显集中趋势) |
> **练习1**:在“概率基础练习.xlsx”文件的表单“练习1”中有一组用户订单支付金额的数据计算订单的均值、中位数、众数。
>
> **练习2**在“概率基础练习.xlsx”文件的表单“练习2”中有一组商品销售量的数据现计划设定一个阈值对阈值以下的商品对应的分销商进行优化应该选择什么作为阈值比较合适
### 数据的离散趋势
如果说数据的集中趋势说明了数据最主要的特征是什么那么数据的离散趋势则体现了这个特征的稳定性。例如A地区冬季平均气温`0`摄氏度,最低气温`-10`摄氏度B地区冬季平均气温`-2`摄氏度,最低气温`-4`摄氏度如果你是一个特别怕冷的人在选择A和B两个区域作为工作和生活的城市时你会做出怎样的选择
1. 极值就是最大值maximum、最小值minimum代表着数据集的上限和下限。
2. 极差:又称“全距”,是一组数据中的最大观测值和最小观测值之差,记作$R$。一般情况下,极差越大,离散程度越大,数据受极值的影响越严重。
3. 方差:将每个值与均值的偏差进行平方,然后除以总数据量得到的值。简单来说就是表示数据与期望值的偏离程度。方差越大,就意味着数据越不稳定、波动越剧烈,因此代表着数据整体比较分散,呈现出离散的趋势;而方差越小,意味着数据越稳定、波动越平滑,因此代表着数据整体比较集中。
- 总体方差:$$ \sigma^2 = \frac {\sum_{i=1}^{N}(X_i - \mu)^2} {N} $$。
- 样本方差:$$ S^2 = \frac {\sum_{i=1}^{N}(X_i - \bar{X})^2} {N-1} $$。
4. 标准差:将方差进行平方根运算后的结果,与方差一样都是表示数据与期望值的偏离程度。
- 总体标准差:$$ \sigma = \sqrt{\frac{\sum_{i=1}^{N}(X_i - \mu)^2}{N}} $$。
- 样本标准差:$$ S = \sqrt{\frac{\sum_{i=1}^{N}(X_i - \bar{X})^2}{N-1}} $$。
> **练习3**:复制“概率基础练习.xlsx”文件的表单“练习1”将复制的表单命名为“练习3”计算订单支付金额的最大值、最小值、极差、方差和标准差。
### 数据的频数分析
频数分析是指用一定的方式将数据分组,然后统计每个分组中样本的数量,再辅以图表(如直方图)就可以更直观的展示数据分布趋势的一种方法。
频数分析的意义:
1. 大问题变小问题,迅速聚焦到需要关注的群体。
2. 找到合理的分类机制,有利于长期的数据分析(维度拆解)。
例如一个班有40个学生考试成绩如下所示
```
73, 87, 88, 65, 73, 76, 80, 95, 83, 69, 55, 67, 70, 94, 86, 81, 87, 95, 84, 92, 92, 76, 69, 97, 72, 90, 72, 85, 80, 83, 97, 95, 62, 92, 67, 73, 91, 95, 86, 77
```
用上面学过的知识,先解读学生考试成绩的数据。
均值81.275中位数83众数95。
最高分97最低分55极差42方差118.15标准差10.87。
但是仅仅依靠上面的数据是很难对一个数据集做出全面的解读我们可以把学生按照考试成绩进行分组如下所示大家可以自行尝试在Excel或用Python来完成这个操作。
| 分数段 | 学生人数 |
| -------- | -------- |
| <60 | 1 |
| [60, 65) | 1 |
| [65, 69) | 5 |
| [70, 75) | 6 |
| [75, 80) | 3 |
| [80, 85) | 6 |
| [85, 90) | 6 |
| [90, 95) | 6 |
| >=95 | 6 |
> **练习4**:在“概率基础练习.xlsx”文件的表单“练习4”中有某App首页版本迭代上线后的A/B测试数据数据代表了参与测试的用户7日的活跃天数请分析A组和B组的数据并判定哪组表现更优。
>
> **练习5**:在“概率基础练习.xlsx”文件的表单“练习5”中有某App某个功能迭代上线后的A/B测试数据数据代表了参与测试的用户30日的产品使用时长请分析A组和B组的数据并判定哪组表现更优。
### 数据的概率分布
#### 基本概念
1. 随机试验:在相同条件下对某种随机现象进行观测的试验。随机试验满足三个特点:
- 可以在相同条件下重复的进行。
- 每次试验的结果不止一个,事先可以明确指出全部可能的结果。
- 重复试验的结果以随机的方式出现(事先不确定会出现哪个结果)。
2. 随机变量:如果$X$指定给概率空间$S$中每一个事件$e$有一个实数$X(e)$,同时针对每一个实数$r$都有一个事件集合$A_r$与其相对应,其中$A_r=\{e: X(e) \le r\}$,那么$X$被称作随机变量。从这个定义看出,$X$的本质是一个实值函数,以给定事件为自变量的实值函数,因为函数在给定自变量时会产生因变量,所以将$X$称为随机变量。
- 离散型随机变量:数据可以一一列出。
- 连续型随机变量:数据不可以一一列出。
如果离散型随机变量的取值非常庞大时,可以近似看做连续型随机变量。
3. 概率质量函数/概率密度函数:概率质量函数是描述离散型随机变量为特定取值的概率的函数,通常缩写为**PMF**。概率密度函数是描述连续型随机变量在某个确定的取值点可能性的函数,通常缩写为**PDF**。二者的区别在于,概率密度函数本身不是概率,只有对概率密度函数在某区间内进行积分后才是概率。
#### 离散型分布
1. 伯努利分布(*Bernoulli distribution*):又名**两点分布**或者**0-1分布**是一个离散型概率分布。若伯努利试验成功则随机变量取值为1。若伯努利试验失败则随机变量取值为0。记其成功概率为$p (0 \le p \le 1)$,失败概率为$q=1-p$,则概率质量函数为:
$$ {\displaystyle f_{X}(x)=p^{x}(1-p)^{1-x}=\left\{{\begin{matrix}p&{\mbox{if }}x=1,\\q\ &{\mbox{if }}x=0.\\\end{matrix}}\right.} $$
2. 二项分布(*Binomial distribution*$n$个独立的是/非试验中成功的次数的离散概率分布,其中每次试验的成功概率为$p$。一般地,如果随机变量$X$服从参数为$n$和$p$的二项分布,记为$X\sim B(n,p)$。$n$次试验中正好得到$k$次成功的概率由概率质量函数给出,$\displaystyle f(k,n,p)=\Pr(X=k)={n \choose k}p^{k}(1-p)^{n-k}$,对于$k= 0, 1, 2, ..., n$,其中${n \choose k}={\frac {n!}{k!(n-k)!}}$。
3. 泊松分布(*Poisson distribution*适合于描述单位时间内随机事件发生的次数的概率分布。如某一服务设施在一定时间内受到的服务请求的次数、汽车站台的候客人数、机器出现的故障数、自然灾害发生的次数、DNA序列的变异数、放射性原子核的衰变数等等。泊松分布的概率质量函数为$P(X=k)=\frac{e^{-\lambda}\lambda^k}{k!}$,泊松分布的参数$\lambda$是单位时间(或单位面积)内随机事件的平均发生率。
> **说明**:泊松分布是在没有计算机的年代,由于二项分布的运算量太大运算比较困难,为了减少运算量,数学家为二项分布提供的一种近似。
#### 连续型分布
1. 均匀分布(*Uniform distribution*):如果连续型随机变量$X$具有概率密度函数$f(x)=\begin{cases}{\frac{1}{b-a}} \quad &{a \leq x \leq b} \\ {0} \quad &{\mbox{other}}\end{cases}$,则称$X$服从$[a,b]$上的均匀分布,记作$X\sim U[a,b]$。
2. 指数分布(*Exponential distribution*):如果连续型随机变量$X$具有概率密度函数$f(x)=\begin{cases} \lambda e^{- \lambda x} \quad &{x \ge 0} \\ {0} \quad &{x \lt 0} \end{cases}$,则称$X$服从参数为$\lambda$的指数分布,记为$X \sim Exp(\lambda)$。指数分布可以用来表示独立随机事件发生的时间间隔,比如旅客进入机场的时间间隔、客服中心接入电话的时间间隔、知乎上出现新问题的时间间隔等等。指数分布的一个重要特征是无记忆性(无后效性),这表示如果一个随机变量呈指数分布,它的条件概率遵循:$P(T \gt s+t\ |\ T \gt t)=P(T \gt s), \forall s,t \ge 0$。
3. 正态分布(*Normal distribution*):又名**高斯分布***Gaussian distribution*),是一个非常常见的连续概率分布,经常用自然科学和社会科学中来代表一个不明的随机变量。若随机变量$X$服从一个位置参数为$\mu$、尺度参数为$\sigma$的正态分布,记为$X \sim N(\mu,\sigma^2)$,其概率密度函数为:$\displaystyle f(x)={\frac {1}{\sigma {\sqrt {2\pi }}}}e^{-{\frac {\left(x-\mu \right)^{2}}{2\sigma ^{2}}}}$。
<img src="normal-distribution.png" width="600">
“3$\sigma$法则”:
<img src="3sigma.png" height="600">
4. 伽马分布(*Gamma distribution*):假设$X_1, X_2, ... X_n$为连续发生事件的等候时间,且这$n$次等候时间为独立的,那么这$n$次等候时间之和$Y$$Y=X_1+X_2+...+X_n$)服从伽玛分布,即$Y \sim \Gamma(\alpha,\beta)$,其中$\alpha=n, \beta=\lambda$,这里的$\lambda$是连续发生事件的平均发生频率。
5. 卡方分布(*Chi-square distribution*):若$k$个随机变量$Z_1,Z_2,...,Z_k$是相互独立且符合标准正态分布数学期望为0方差为1的随机变量则随机变量$Z$的平方和$X=\sum_{i=1}^{k}Z_i^2$被称为服从自由度为$k$的卡方分布,记为$X \sim \chi^2(k)$。

View File

@ -162,7 +162,7 @@ Hive的数据类型如下所示。
set hive.exec.max.dynamic.partitions.pernode=10000;
```
5. 拷贝数据。
5. 拷贝数据Shell命令
```Shell
hdfs dfs -put /home/ubuntu/data/user_trade/* /user/hive/warehouse/demo.db/user_trade