基础
执行顺序
DCL
管理用户
-- 查询用户
use mysql;
select * from user;
-- 创建用户
create user '用户名'@'主机名' IDENTFIFD by '新密码';
-- 例
创建用户itcast,只能在当前主机localhost访问 密码123;
create user 'itcast'@'localhost' IDENTFIFD by '123'; -- 只查询到一个数据库
创建用户heima,可以在任意主机访问该数据库 密码123;
create user 'heima'@'%' IDENTFIFD by '123';
-- 修改用户密码
alter user '用户名'@'主机名' IDENTFIFD with mysql_native_password by '新密码';
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123456';
--删除用户
drop user '用户名'@'主机名' ;
-- 主机名可以使用%通配
权限控制
-- 查询权限
show grants for '用户名'@'主机名';
-- 授予权限
grant 权限列表 on 数据库名.表名 to '用户名'@'主机名';
--撤销权限
revoke 限列表 on 数据库名.表名 from '用户名'@'主机名';
-- 例
show grants for 'heima'@'%' ;
grant all on itcast.* to 'heima'@'%' ;
revoke all on itcast.* from 'heima'@'%' ;
-- 注意
多个权限之间,使用逗号分隔
授权时,数据库名和表名可以使用*进行通配,代表所有
函数
lapd(str,n,pad) 左填充,用字符串pad对str的左边进行填充,达到n个字符串长度
--案例:通过数据库的函数,生成一个六位数的随机验证码
select lpad (round(rand()*1000000,0),6,'0');
-- datediff (两个天数相差)
select datediff('2021-10-01','2021-12-01'); -- 返回-61
约束
注意:约束是作用于表中字段上的,可以在创建表/修改表的时候添加约束
id 主键自动增长
name 不为空并且唯一
age 大于0小于等于120
status 默认值1
gender
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 '用户表';
外键约束
--创建外键
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;
删除/更新行为
更新 子表一起更新
删除 有相应外键的记录都被删除了
多表查询
--内连接
隐式 from 表A,表B where 条件
显示 表A inner join 表B on 条件
-- 自连接
select a.name , b.name from emp a ,emp b where a.manager_id=b.id
--联合查询 union(去重) / union all
select * from emp where salary >5000
union
select * from emp where age < 50
--注意 两个查询的字段列数要一样字段类型也需要保持一致
-- 子查询
select * from emp dept_id = (select id from dept where name = '销售部')
并发事务问题
事务隔离级别(✔是会出现这个问题)
--查看事务隔离级别
select @@transaction_isolation
--设置事务隔离级别
set session transaction_isolation level read uncommitted;
--事务隔离级别安全越高性能越差