MySQL基础篇(二)

MySQL函数

创建表

create table student
(
    id   int auto_increment primary key comment '主键ID',
    name varchar(10) comment '姓名',
    no   varchar(10) comment '学号'
) comment '学生表';

insert into student
values (null, '黛绮丝', '2000100101'),
       (null, '谢逊',
        '2000100102'),
       (null, '殷天正', '2000100103'),
       (null, '韦一笑', '2000100104');

create table course
(
    id   int auto_increment primary key comment '主键ID',
    name varchar(10) comment '课程名称'
) comment '课程表';

insert into course
values (null, 'Java'),
       (null, 'PHP'),
       (null, 'MySQL'),
       (null, 'Hadoop');

create table student_course
(
    id        int auto_increment comment '主键' primary key,
    studentid int not null comment '学生ID',
    courseid  int not null comment '课程ID',
    constraint fk_courseid foreign key (courseid) references course (id),
    constraint fk_studentid foreign key (studentid) references student (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);

-- 创建dept表,并插入数据
create table dept(
    id int auto_increment comment 'ID' primary key,
    name varchar(50) not null comment '部门名称'
)comment '部门表';

INSERT INTO
    dept (id, name)
VALUES
    (1, '研发部'), (2, '市场部'),(3, '财务部'), (4,'销售部'), (5, '总经办'), (6, '人事部');

-- 创建emp表,并插入数据
create table emp(
    id int auto_increment comment 'ID' primary key,
    name varchar(50) not null comment '姓名',
    age int comment '年龄',
    job varchar(20) comment '职位',
    salary int comment '薪资',
    entrydate date comment '入职时间',
    managerid int comment '直属领导ID',
    dept_id int comment '部门ID'
)comment '员工表';

-- 添加外键
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references dept(id);

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


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

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

​ MySQL中内置了很多字符串函数,常用的几个如下:

函数功能
CONCAT ( S1,S2,…Sn )字符串拼接,将S1,S2,…Sn 拼写成一个字符串
LOWER ( str )将字符串str全部转为小写
UPPER ( str )将字符串str全部转为小写
LPAD ( str, n, pad )左填充,用字符串pad 对str 的左边进行填充,达到n个字符串长度
RPAD (str, n, pad )右填充,用字符串pad 对str 的右边进行填充,达到n个字符串长度
TRIM ( str )去掉字符串头部和尾部的空格
UBSTRING ( str, start, len )返回从字符串str 从start 位置的len 个长度的字符串
使用代码:
select concat('hello','MySQL');

select lower('HELLO');

select upper('hello');

select lpad('01',5,'-');

select rpad('01',5,'-');

select trim('   sdw dwadkasdwa  ') '123';

select substring('hello Mysql',7,5);
数值函数

​ 常见的数值函数如下:

函数功能
CEIL ( x )向上取整
FLOOR ( x )向下取整
MOD ( x, y )返回 x/y 的模
RAND ()返回 0 ~ 1 内的随机数
ROUND (x,y)求参数 x 的四舍五入的值,保留 y 位小数
使用代码:
select ceil(1.5);

select floor(1.4);

select mod(3,7);

select rand();

select round(2.3452);

select lpad(round(rand()*1000000),6,'0');
日期函数

​ 常见的日期函数如下:

函数功能
CURDATE ()返回当前日期
CURTIME ()返回当前时间
NOW ()返回当前日期和时间
YEAR (date)获取指定data的年份
MONTH (date)获取指定date的月份
DAY (date)获取指定date的日期
DATE_ADD (date, INTERVAL expr type)返回一个日期/时间值加上一个时间间隔expr后的时间值
DATEDIFF (date1, date2)返回起始时间date1 和 结束时间date2 之间的天数
使用代码:
select curdate();

select curtime();

select now();

select year(now());

select month(now());

select day(now());

select date_add(now(), interval 70 year );
select date_add(now(), interval 70 day );
select date_add(now(), interval 70 month );

select datediff('2028-11-07','2020-01-07');
流程函数

​ 流程函数也是很常用的一类函数,可以在SQL语句中实现条件筛选,从而提高语句的效率。

函数功能
IF ( value, t, f )如果value为true, 则返回 t,否则返回 f
IFNULL ( value1, value2 )如果value不为null,则返回value1,否则返回value2
CASE WHEN [ val1 ] THEN [ res1 ] … ELSE [ default ] END如果val1为true,返回res1,…否则返回default默认值
CASE [ expr ] WHEN [ val1 ] THEN [ res1 ] … ELSE [ default ] END如果expr 的值等于val1,返回res1,…否则返回default默认值
使用代码:
select if(true,'ok','e');

select ifnull(null,'w');
select
    id,
    name,
    (case when score.math >= 85 then '优秀' when score.math >=60 then '及格' else '不及格' end) as '数学',
    (case when score.english >= 85 then '优秀' when score.english >=60 then '及格' else '不及格' end) as '英语',
    (case when score.chinese >= 85 then '优秀' when score.chinese >=60 then '及格' else '不及格' end) as '语文'
from score;

在这里插入图片描述

约束

  1. 概念:约束是作用域表中字段上的规则,用于限制存储在表中数据。

  2. 目的:保证数据库中数据的正确、有效性和完整性。

  3. 分类:

    约束描述关键字
    非空约束限制该字段的数据不能为nullNOT NULL
    唯一约束保证该字段的所有数据都是唯一、不重复的UNIQUE
    主键约束逐渐是一行数据的唯一标识,要求非空且唯一PRIMARY KEY
    默认约束保存数据时,如果未指定该字段的值,则采用默认值DEFAULT
    检查约束(8.0.16版本之后)保证字段值满足某一个条件CHECK
    外键约束用来让两张表的数据之间建立连接,保证数据的一致性和完整性FOREIGN KEY

注意:约束是作用于表中字段上的,可以在创建表/修改表的时候添加约束。

根据需求,完成表结构的创建

字段名字段含义字段类型约束条件约束关键字
idID唯一标识int主键,并且自动增长PRIMARY KEY,AUTO_INCREMENT
name姓名varchar(10)不为空,并且唯一NOT NULL,UNIQUE
age年龄int大于0,并且小于等于120CHECK
status状态char(1)如果没有指定该值,默认为1DEFAULT
gender性别char(1)
create table user(
    id int primary key auto_increment comment 'ID',
    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 '用户表';
外键约束
  • 语法

    添加外键

    create table 表名(
    	字段名 数据类型,
        ……
        [constraint] [外键名称] foreign key(外键字段名) references 主表(主表列名)
    );
    
    alter table 表名 add constraint 外键名称 foreign key(外键字段名) references 主表(主表列名)
    

    删除外键

    alter table 表名 drop foreign key 外键名;
    
  • 删除/更新行为

    行为说明
    NO ACTION当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则不允许删除/更新。(与RESTRICT一致)
    RESTRICT当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则不允许删除/更新。(与NO ACTION一致)
    CASCADE当在父表中删除对应记录时,首先检查该记录是否有对应外键,如果有则设置子表中该外键值为null(这就要求该外键允许去null)
    SET NULL当在父表中删除对应记录时,首先检查记录是否有对应外键,如果有则设置子表中该外键值为null(这就要求外键允许取null)
    SET DEFAULT父表有变更时,子表将外键列设置成一个默认的值(Innodb不支持)
alter table 表名 add constraint 外键名称 foreign key (外键字段) references 主表名(主表字段名) on update cascade on delete cascade;

多表查询

多表关系
  1. 一对多(多对一)
    • 在多的一方建立外键,指定一的一方的主键
  2. 多对多
    • 建立第三张中间表,中间表至少包含两个外键,分别关联两方主键
  3. 一对一
    • 在任意一方加入外键,关联另外一方的主键,并且设置外键为唯一的(UNIQUE)
多表查询
  • 概述:指从多张表中查询数据

  • 笛卡尔积:笛卡尔乘积是指在数学中,两个 A集合和 B集合的所有组合情况。(在多表查询时,需要消除无效的笛卡尔积)

  • 多表查询分类

    • 连接查询

      ​ 内连接:相当于查询A、B交集数据

      ​ 外连接:

      ​ 左外连接:查询左表所有数据,以及两张表交集部分数据

      ​ 右外连接:查询右表所有数据,以及两张表交集部分数据

      ​ 自连接:当前表与自身的连接查询,自连接必须使用表别名

    • 子查询

连接查询
连接查询-内连接

内连接查询语法:

  • 隐式内连接

    select 字段列表 from 表1,表2 where 条件…;
    
  • 显示内连接

    select 字段列表 from 表1 [inner] join 表2 on 连接条件…;
    

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

连接查询-外连接

外连接查询语法:

  • 左外连接

    select 字段列表 from 表1 left [outer] join 表2 on 条件…;
    
  • 右外连接

    select 字段列表 from 表1 right [outer] join 表2 on 条件…;
    
连接查询-自连接

自连接查询语法:

select 字段列表 from 表A 别名A join 表A 别名B on 条件…;

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

select a.name '员工',b.name '领导' from emp a join emp b on a.managerid = b.id;
select a.name '员工',b.name '领导' from emp a left join emp b on a.managerid = b.id;

**注意:**不添加left,emp表关联表字段值为null,数据将不显示。

联合查询-union,union all

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

select 字段列表 from 表A …
union [all]
select 字段列表 from 表B …;

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

union all 会将全部的数据直接合并在一起,union会对合并之后的数据去重。

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

    select * from t1 where column1 = (select column1 from t2);
    

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

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

    • 标量子查询(子查询结果为单个值)
    • 列子查询(子查询结果为一列)
    • 行子查询(子查询结果为一行)
    • 表子查询(子查询结果为多行多列)
  • 根据子查询位置,分为:WHERE之后、FROM之后、SELECT之后

标量子查询

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

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

select * from t1 where 字段列表 = (select 字段列表 from t1 where 条件);
列子查询

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

常用的操作符:IN、NOT IN、ANY、SOME、ALL

操作符描述
IN在指定的集合范围之内,多选一
NOT IN不在指定的集合范围之内
ANY子查询返回列表中,有任意一个满足即可
SOME与ANY等同,使用SOME的地方都可以使用ANY
ALL子查询返回列表的所有值都必须满足
/**根据部门ID, 查询员工信息*/
select * from emp where dept_id in (select id from dept where name in ('市场部','销售部'));

/** 比 财务部 所有人工资都高的员工信息*/
select * from emp where salary > all (select salary from emp where dept_id = (select id from dept where name = '财务部'));

/** 比研发部其中任意一人工资高的员工信息*/
select * from emp where salary > any (select salary from emp where dept_id = (select id from dept where name = '研发部'));
行子查询

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

常用的操作符:= 、( ) 、IN 、NOT IN

select * from emp where (salary,managerid) = (select salary,managerid from emp where name = '张无忌');
表子查询

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

常用的操作符:IN

select * from emp where (salary,job) in (select salary,job from emp where name in ('张无忌','宋远桥') );

# 查询入职日期是 "2006-01-01" 之后的员工信息 , 及其部门信息
select e.*,d.* from (select * from emp where entrydate > '2006-01-01') e left join dept d on e.dept_id = d.id;
小练习
# 查询员工的姓名、年龄、职位、部门信息 (隐式内连接)
select e.name,e.age,e.job,d.name from emp e,dept d where e.dept_id = d.id;

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

# 查询拥有员工的部门ID、部门名称
select * from dept d where d.id in (select dept_id from emp where dept_id is not null);
select distinct d.id,d.name from dept d,emp e where e.dept_id = d.id;

# 查询所有年龄大于40岁的员工, 及其归属的部门名称; 如果员工没有分配部门, 也需要展示出来(外连接)
select e.*,d.name from (select * from emp where age > 40) e left join dept d on e.dept_id = d.id;
select e.*,d.name from emp e left join dept d on e.dept_id = d.id where e.age > 40;

# 查询所有员工的工资等级
select e.*,s.grade from emp e,salgrade s where e.salary >= s.losal and e.salary <= s.hisal;
select e.*,s.grade from emp e,salgrade s where e.salary between s.losal and s.hisal;

# 查询 "研发部" 所有员工的信息及 工资等级
select e.*, s.grade from emp e,salgrade s,dept d where (e.salary between s.losal and s.hisal) and e.dept_id = d.id and d.name = '研发部';

# 查询 "研发部" 员工的平均工资
select avg(e.salary) from emp e,dept d where e.dept_id = d.id and d.name = '研发部';

# 查询工资比 "灭绝" 高的员工信息。
select salary from emp where name ='灭绝';
select * from emp where salary > ( select salary from emp where name ='灭绝' );

#  查询比平均薪资高的员工信息
select * from emp where salary > ( select avg(salary) from emp );

# 查询低于本部门平均工资的员工信息
select *, (select avg(e1.salary) from emp e1 where e1.dept_id = e2.dept_id) '平均' from emp e2 where e2.salary < (select avg(e1.salary) from emp e1 where e1.dept_id = e2.dept_id);

# 查询所有的部门信息, 并统计部门的员工人数
select d.id,d.name,(select count(*) from emp where dept_id = d.id) '人数' from dept d ;

# 查询所有学生的选课情况, 展示出学生名称, 学号, 课程名称
select s.name, s.id, c.name from student s,course c,student_course sc where sc.studentid = s.id && sc.courseid = c.id;

事务

事务简介

事务:是一组操作的集合,它是一个不可分割的工作单位,事务会把所有的操作转为一个整体一起向系统提交或撤销操作请求,即这些操作要么同时成功,要么同时失败。

默认MySQL的事务是自动提交的,也就是说,当执行一条DML语句,MySQL会立即隐式的提交事务。

事务操作
# 查看/设置事务提交方式
select @@autocommit;
set @@autocommit = 0;

# 开始事务
start transaction;
# 开始事务
begin;
  • 提交事务

    commit ;
    
  • 回滚事务

    rollback ;
    
事务四大特性(ACID)
  • 原子性(Atomicity):事务是不可分割的最小操作单位,要么全部成功,要么全部失败。
  • 一致性(Consistency):事务完成时,必须使所有的数据都保持一致状态。
  • 隔离性(Isolation):数据库系统提供的隔离机制,保证事务在不受外部并发操作影响的独立环境下运行。
  • 持久性(Durability):事务一旦提交或回滚,它对数据库中的数据的改变就是永久的。
并发事务问题
问题描述
脏读一个事务读到另外一个事务还没有提交的数据。
不可重复读一个事务先后读取同一条记录,但两次读取的数据不同,称之为不可重复读。
幻读一个事务按照条件查询数据时,没有对应的数据行,但是在插入数据时,又发现这行数据时,又发现这行数据已经存在,好像出现了 “幻影” 。
并发事务隔离级别
隔离级别脏读不可重复读幻读
Read uncommitted
Read committed×
Repeateble Read(默认)××
Serializable×××
# 查看事务隔离级别
select @@TRANSACTION_ISOLATION;

# 设置事务隔离级别
SET [SESSION|GLOBAL] TRANSACTION ISOLATION LEVEL {READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SERIALIZABLE}

**注意:**事务隔离级别越高,数据越安全,但是性能越低。

ation):数据库系统提供的隔离机制,保证事务在不受外部并发操作影响的独立环境下运行。

  • 持久性(Durability):事务一旦提交或回滚,它对数据库中的数据的改变就是永久的。
并发事务问题
问题描述
脏读一个事务读到另外一个事务还没有提交的数据。
不可重复读一个事务先后读取同一条记录,但两次读取的数据不同,称之为不可重复读。
幻读一个事务按照条件查询数据时,没有对应的数据行,但是在插入数据时,又发现这行数据时,又发现这行数据已经存在,好像出现了 “幻影” 。
并发事务隔离级别
隔离级别脏读不可重复读幻读
Read uncommitted
Read committed×
Repeateble Read(默认)××
Serializable×××
# 查看事务隔离级别
select @@TRANSACTION_ISOLATION;

# 设置事务隔离级别
SET [SESSION|GLOBAL] TRANSACTION ISOLATION LEVEL {READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SERIALIZABLE}

**注意:**事务隔离级别越高,数据越安全,但是性能越低。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值