数据类型
1.数值类型
tinyint,smallint,mediumint,int,integer,bigint,float,double,decimal
其中加上unsigned为无符号也就是其中的数据不能为负数
2.字符串类型
char,varchar,tinyblob,tinytext,blob,text,mediumblob,mediumtext,longblob,longtext
定长字符串的意思为规定了的字符串的长度在内存中不能更改,比如说char(10)那么如果你输入的数据小于10,剩余的空间会用0来表示,而变长字符串则是相反如果你输入的数据没有达到最大限度,系统会自动计算你所需要的长度。
3.日期类型
date,time,year,datetime,timestamp
数据库创建基本操作
create table BasicQuery(
id int comment '编号',
worknum varchar(10) comment '工号',
name varchar(10) comment '姓名',
gender char(1) comment '性别',
age tinyint unsigned comment '年龄'
) comment '员工表';
insert into BasicQuery (id, worknum, name, gender, age)
values (1,'1','小路','男',20),
(2,'2','小师','男',10),
(3,'3','小魏','男',21),
(4,'4','小哲','男',85);
DDL-数据库操作
1.查询所有数据库:show databases
2.查询当前数据库:select database
3.创建数据库:create database【if not exists】数据库名【default charset 字符集】【collate排序规则】
4.删除:drop database【if exists】数据库名
5.使用:use 数据库名
DDL-表操作
1.创建表:create table 表名{字段1 字段1类型【comment 字段1注释,字段2 字段2类型【comment 字段2注释】}最后一个不用加逗号
2.查询当前数据库所有表:show tables
3.查询表结构:desc 表名
4.查询指定表的建表语句:show create table 表名
5.在表中添加数据字段:alter table 表名 add 字段名 类型(长度)【comment 注释】【约束】
6.修改字段名和字段类型:alter table 表名 change 旧字段 新字段 类型(长度)【comment 注释】
7.修改数据类型:alter table 表名 modify 字段名 新数据类型【长度】
8.修改表名:alter table 表名 rename 新表名
9.删除表:drop table 【if exists】表名
指定删除表,并重新创建该表:iruncate table 表名
10.删除字段:alter table 表名 drop username
DML-数据操作
DML-添加数据
1.给指定字段添加数据
insert into 表名 (字段名,字段名1…)values(值1,值2…);
2.给全部字段添加数据
insert 表名 values(值1,值2…);
3.批量添加数据
insert into 表名(字段名1,字段名2…)values(值1,值2…),(值1,值2…);
insert into 表名 values (值1,值2…)(值1,值2…);
代码如下:
注意:插入数据时,指定的字段顺序需要与值的顺序是一一对应的。
字符串和日期型数据应该包含在引号中
插入的数据大小,应该在字段的规定范围内。
insert into adddata (id, workno, name, gender, age, idcard, entrydate) values (1,'1','张无忌','男',38,'123456789012345678','2000-01-01');
select * from adddata;
insert into adddata values (2,'1','张无忌','男',38,'123456789012345678','2000-01-01');
DML-修改数据
update 表名 set 字段名1 = 值1 ,字段名2 = 值2,…[where 条件];
代码如下:
update adddata set id=5 where name = '张无忌';
update adddata set entrydate = '2023-09-24';
update adddata set name = '小路',gender = '女' where id = 1;
DML-删除数据
delete from 表名 【where 条件】如果后面不加where则是删除表中的所有数据,delete 不能删除某一字段的值,只能删除条件中的整条数据。
代码如下:
delete from adddata where id = 1;
delete from adddata;
DQL-查询数据
DQL-基本查询
1.查询多个字段
select 字段1,字段2…from 表名;
select * from 表名(通配符 查询所有字段,但是不建议使用);
2.给字段设置别名
select 字段1 [as 别名1],字段2[as 别名2,]…from 别名;
3.去除重复记录
select distinct 字段列表 from 表名;
select name,age from BasicQuery;
select age as '年龄' from BasicQuery;
select distinct gender from BasicQuery;
DQL-条件查询
以下为条件符号的应用案例
其中占位符 % ,如果x在中间那么要写成**“%x%”**
# 1.查询年龄等于88的员工
select *from emp where age = 88;
# 2.查询年龄小于20的员工的信息
select *from emp where age < 20;
# 3.查询年龄小于等于20的员工信息
select *from emp where age <= 20;
# 4.查询没有身份证号的员工信息
select *from emp where idcard is null ;
# 5.查询有身份证号的员工信息
select *from emp where idcard is not null ;
# 6.查询年龄不等于88的员工信息
select *from emp where age != 88;
select *from emp where age <> 88;
# 7.查询年龄在15岁(包含)到20岁(包含)之间的员工信息
select *from emp where age >= 15 && age <= 20;
select *from emp where age >=15 and age <= 20;
select *from emp where age between 15 and 20;
# 8.查询性别为女且年龄小于25岁的员工信息
select *from emp where gender = '女' and age < 25;
# 9.查询年龄等于18或20或40的员工信息
select *from emp where age = 18 or age = 20 or age = 40;
select *from emp where age in (18,20,40);
# 10.查询姓名为两个字的员工信息 _ %
select *from emp where name like '__';
# 11.查询身份证号最后一位是x的员工信息
select *from emp where idcard like '%x';
DQL-聚合函数
聚合函数将一列数据作为一个整体,进行纵向计算,常见的聚合函数如图所示
语法:select 聚合函数(字段列表) from 表名。
注意:null值不计入计算
# 聚合函数
# 1.统计该企业员工数量
select count(*) from emp;
select count(id) from emp;
# 2.统计该企业员工的平均年龄
select avg(age) from emp;
# 3.统计该企业员工的最大年龄
select max(age) from emp;
# 4.统计该企业员工的最小年龄
select min(age) from emp;
# 5.统计西安地区员工的年龄之和
select sum(age) from emp where workaddress = '西安';
DQL-分组查询
语法:select 字段列表 from 表名 [where 条件] group by 分组字段名[having 分组后过滤条件]
where和having的区别:
1.where是分组之前进行过滤不满足where条件不参与分组,而having则是分组之后对分组之后的结果进行过滤
2.where不能对聚合函数进行判断,而having可以
注意
1.执行顺序:where > 聚合函数>having
2.分组后查询的字段一般为聚合函数和分组字段查询其他字段无任何意义
# 分组查询
# 1.根据性别分组,统计男性员工,和女性员工的数量
select gender,count(*) from emp group by gender;
# 2.根据性别分组,统计男性员工和女性员工的平均年龄
select gender,avg(age) from emp group by gender;
# 3.查询年龄小于45的员工并根据工作地址分组获取员工数量大于等于3的工作地址 addresd_count 为count(*)的别名后面就不用再写count(*);
select workaddress,count(*) address_count from emp where age < 45 group by workaddress having address_count >= 3;
DQL-排序查询
语法:select 字段列表 from 表名 order by 字段1 排序方式1,字段2 排序方式2;
asc:升序
desc:降序
注意:如果是多字排序当一个字段值相同时,才会根据第二个字段进行排序
# 排序查询
# 1.根据年龄对公司的员工进行升序排序
select *from emp order by age ;
# select *from emp order by age desc;降序排序
# 2.根据入职时间,对员工进行降序排序
select * from emp order by entrydate desc;
# 3.根据年龄对公司的员工进行升序排序年龄相同再按照入职时间进行降序排序
select *from emp order by age,entrydate desc ;
# select *from emp order by age asc ,entrydate asc ;升序排序
DQL-分页查询
语法:select 字段列表 from 表名 limit 起始索引,查询记录数;
注意:
1.起始索引从0开始,起始索引 = (查询页码 - 1)*每页显示记录数。
2.分页查询是数据的方言,不同的数据库有不同的实现,MySQL中是limit
3.如果查询的是每一页数据,起始索引可以省略直接简写为limit 10
# 分页查询
# 1.查询第1页员工数据,每页展示10条记录
select * from emp limit 0,10;
# select * from emp limit 10;起始索引为0可以省略不写
# 2.查询第2页员工数据,每页展示10条记录------->(页码 - 1 )* 每页记录数 = 起始索引
select * from emp limit 10,10;
DQL-执行和编写顺序
编写顺序:
select 字段列表
from 表名列表
where 条件列表
group by 分组字段列表
having 分组后条件列表
order by 排序字段列表
limit 分页参数
执行顺序:
from 表名列表
where 条件列表
group by 分组字段列表
having 分组后条件列表
select 字段列表
order by 排序字段列表
limit 分页参数
DCL-管理用户
DCL-管理用户
1.查询用户
use mysql;
select * from user;
2.创建用户
create user ‘用户名’@‘主机名’ identified by ‘密码’;
3.修改用户密码
alter user ‘用户名’@‘主机名’ identified with mysql_native_password by ‘新密码’;
4.删除用户
drop user ‘用户名’@‘主机名’;
# dcl语句
# 1.创建用户itcast只能够在当前主机localhost访问密码123456
create user 'itcast' @ 'localhost' identified by '123456';
# 2.创建用户heima可以在任意主机访问该数据库密码123456
create user 'heima' @'%' identified by '123456';
# 3.修改heima的访问密码为1234
alter user 'heima' @'%' identified with mysql_native_password by '1234';
# 删除用户
drop user 'itcast' @ 'localhost';
DCL-权限控制
1.查询权限
show grants for ‘用户名’@‘主机名’;
2.授予权限
grant 权限列表 on 数据库名.表名 to ‘用户名’@‘主机名’;
3.撤销权限
revoke 权限列表 on 数据库名.表名 from ‘用户名’@‘主机名’;
# 查询权限
show grants for 'heima' @'%';
# 授予权限
grant all on itcast.* to 'heima' @'%';
# 撤销权限
revoke all on itcast.* from 'heima' @'%';
DCL-字符串函数
# concat
select concat('hello',' mysql');
# lower
select lower('Hello');
# upper
select upper('hello');
# lpad
select lpad('01',5,'_');
# rpad
select rpad('01',5,'_');
# trim
select trim(' hello mysql ');
# substring
select substring('hello masql',1,5);
DCL-数值函数
# 数值函数
# ceil
select ceil(1.1);
# floor
select floor(1.9);
# mod
select mod(7,4);
# rand
select rand();
# round
select round(2.345,2);
# 通过数据库的函数生成一个六位数的随机数
select lpad(round(rand()*1000000,0),6,'0');
DCL-日期函数
# 日期函数
# curdate
select curdate();
# curtime
select curtime();
# now
select now();
# year,month,day
select year(now());
select month(now());
select day(now());
# date_add
select date_add(now(),INTERVAL 70 day );
# datediff
select datediff('2021-12-01','2021-10-01');
# 案例:查询所有员工的入职天数并根据入职天数倒序排序
select name,datediff(curdate(),entrydate) as 'entrydats' from emp order by entrydats desc ;
DCL-流程函数
# 流程控制函数
# if
select if(false,'ok','error');
# ifnull
select ifnull('ok','Default');
select ifnull('','Default');
select ifnull(null,'Default');
# case when then else end
# 需求:查询emp表的员工姓名和工作地址
select
name,
(case workaddress when '北京' then '一线城市' when '上海' then '一线城市' else '二线城市' end) as '工作地址'
from emp;
# 统计班级各个学员的成绩,展示的规则如下:
# 85 优秀 60及格 59 不及格
create table score(
id int comment 'ID',
name varchar(20) comment '姓名',
math int comment '数学',
english int comment '英语',
chinese int comment '语文'
) comment '学员成绩表';
insert into score(id,name,math,english,chinese) values (1,'tom',67,88,95),
(2,'rose',23,66,90),
(3,'jack',56,98,76);
select
id,
name,
(case when math >=85 then '优秀' when math >=60 then '及格' else '不及格' end)'数学',
(case when english >=85 then '优秀' when english >=60 then '及格' else '不及格' end)'英语',
(case when chinese >=85 then '优秀' when chinese >=60 then '及格' else '不及格' end)'数学'
from score;
约束
概念:约束;作用于表中字段上的规则,用于限制存储在表中的数据,目的为保证数据库中数据的正确、有效性和完整性
分类为:
# 约束
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 '用户表';
# 插入数据
insert into user(name,age,status,gender) values ('tom1',19,'1','男'),
('tom2',25,'0','男'),
('tom3',14,'2','女');
外键约束
概念:外键用来让两张表的数据之间建立连接,从而保证数据的一致性和完整性
添加外键
(建表后添加外键)语法:alter table 表名 add constraint 外键名称 foreign key (外键字段名)references 主表(主表列名);
(建表中添加外键)语法:create table 表名(
字段名 数据类型
[constraint][外键字段名] foreign(外键字段名)refernces 主表(主表列名)
)
删除外键
alter table 表名 drop foreign key 外键名称;
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,'总经办');
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 int comment '入职时间',
managerid int comment '直属领导ID',
dept_id int comment '部门ID'
) comment '员工表';
alter table emp change entrydate entrydats date;
# alter table 表名 change 旧字段 新字段 类型(长度)
insert into emp (id, name, age, job, salary, entrydats, 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);
# 添加外键
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references dept(id);
# 删除外键
alter table emp drop foreign key fk_emp_dept_id;
约束删除和更新行为
**语法:**alter table 表名 add constraint 外键名称 foreignkey (外键字段) references 主表名 (主表字段名)on update cascade on delete cascade;
# 外键的删除和更新行为
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references dept (id) on update cascade on delete cascade
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references dept(id) on update set null on delete set null ;
多表关系
多表关系分为三种;一对多,多对多,一对一
一对一关系多用于单表拆分,
实现:在任意一方加入外键关联另外一方的主键,并且设置外键为唯一的(unique)
多对多关系用于两张表之间每条语句对应每条语句
实现:建立第三张中间表中间表至少包含两个外键,分别关联两方主键
# 多对多关系
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,'小段','2000200103'),
(null,'小伟','2000100104');
create table course(
id int auto_increment primary key comment '主键ID',
name varchar(10) comment '课程名称'
)connection '课程表';
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);
多表查询
指从多张表查询数据,查询过程中会产生笛卡尔积,笛卡尔积指在数学中两个集合a和集合b的所有组合情况所以在多表查询过程中要消除无效的笛卡尔积。
多表查询分为几类:
分别是连接查询中的内连接:相当于查询ab交集的部分数据,外连接:左外连接查询左表所有数据,以及两张表交集部分数据,右外连接查询右表所有数据以及两张表交集部分数据,自连接当前表与自身的连接查询自连接必须使用表别名,还有一种就是子查询
内连接
隐式内连接查询语法:select 字段列表 from 表1,表2 where 条件…
显示内连接查询语法: select 字段列表 from 表1 [inner] join 表2 on 连接条件…
内连接查询的是两张表交集的部分。
# 1.内连接演示
# 表结构:emp,dept(隐式连接)
# 连接条件:emp.detp_id = dept.id
select emp.name,dept.name from emp,dept where emp.dept_id = dept.id;
# 2.查询每一个员工的姓名及关联的部门的名称(显示连接)
# 表结构:emp,dept
# 连接条件:emp.dept_id = dept.id
select e.name,d.name from emp e inner join dept d on e.dept_id = d.id
左右连接
左连接查询语法:select 字段列表 from 表1 left [outer] join 表2 on 条件…
相当于查询左表的所有数据包含表1和表2交集部分的数据
右连接查询语法:select 字段列表 from 表1right [outer] join 表2 on 条件…
相当于查询右表的所有数据包含表1和表2交集部分的数据
# 连接演示
# 1.查询emp表的所有数据和对应的部门信息(左外连接)
select d.*,e.* from emp e left join dept d on e.dept_id = d.id;
# 2.查询dept表的所有数据和对应的员工信息(右外连接)
select d.*,e.*from emp e right join dept d on e.dept_id = d.id;
自连接
自连接查询语法:select 字段列表 from 表a 别名a join 表a 别名b 条件…
自连接查询,可以是内连接也可以是外连接查询
联合查询
对于联合查询就是把多次查询的结果合并起来形成一个新的查询结果集
语法:select 字段列表 from 表a…
union[all]
select 字段列表 from 表b…
注意:联合多表查询的列数要保持一致,字段类型保持一致
union all 会将全部的数据直接合并在一起,union会对合并之后的数据去重
子查询
1.标量子查询
子查询返回的结果是单个值(数字、字符串、日期)最简单的形式称为标量子查询
常用符号位 == =< 等
2.列子查询
# 列子查询
#1.查询销售部和市场部的所有员工信息
#a.查询销售部和市场部的部门id
select id from dept where name = '销售部' or name = '市场部';
#b.根据部门id,查询员工信息
select * from emp where dept_id in (select id from dept where name = '销售部' or name = '市场部');
#2.查询比财务部所有人工资都高的员工信息
#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 = '财务部'));
#3.查询比研发比研发部其中任意一人工资高的员工信息
#a.查询研发部所有人工资
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 = '研发部'));
3.行子查询
子查询返回的结果是一行(可以是多列),这种查询称为行子查询,常用的操作符为:= <> in not in
#行子查询
#1.查询与‘张无忌’的薪资及直属领导相同的员工信息
#a.查询‘张无忌’的薪资及直属领导
select salary,managerid from emp where name = '张无忌';
#b.查询与张无忌的薪资及直属领导相同的员工信息;
select * from emp where (salary,managerid) = (select salary,managerid from emp where name = '张无忌');
4.表子查询
子查询返回的结果是多行多列,这种子查询称为表子查询
常用的操作符:in
#表子查询
#1.查询与‘小路’,‘小宋’的职位和薪资相同的员工信息
#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 = '小宋');
#2.查询入职日期是‘2006-02-02’之后的员工信息
#a.入职日期是‘2003-02-02’之后的员工信息
select * from emp where emp.entrydats > '2003-01-01';
#b.查询这部分员工,对应的部门信息;
select e.*,d.* from (select *from emp where emp.entrydats > '2006-01-01') e left join dept d on e.dept_id = d.id;
事务
事务操作
方法一
查看或设置事务提交方式
select @@autocommit;
set @@autocommit = 0;
set @@autocommit = 1;系统默认自动提交;
提交事务:commit;
回滚事务:rollback;当语句执行出错时使用此语句
方法二
手动开启事务:start transaction或begin
提交事务:commit
回滚事务:rollback
create table account(
id int auto_increment primary key comment '主键ID',
name varchar(10) comment '姓名',
money int comment '余额'
) comment '账户表'
insert into account(id,name,money) values (null,'张三',2000),(null,'李四',2000);
#恢复数据
update account set money = 2000 where name = '张三' or name = '李四';
select @@autocommit;
#设置为手动提交
set @@autocommit = 1;
#转账操作
#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 = '李四';
#提交事务
commit ;
#回滚事务
rollback ;
#方式二
#转账操作
start transaction ;
#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 = '李四';
#提交事务
commit ;
#回滚事务
rollback ;