一、分类
- DDL定义
- DML操作
- DQL查询
- DCL控制
二、规范格式
- 不区分大小写,关键字建议大写;
- 注释:
--单行注释 # 单行注释(MySQL特有) /* 多行注释 */
- “字符串”和“日期”用双引号包含;
三、SQL语句
-
DDL定义
Data Definition Language数据定义语言,用来定义数据库对象(数据库,表,字段) 。
数据库对象
-- 数据库操作
SHOW databases;
create database 数据库名;
use 数据库名;
select database();
drop database 数据库名;
表对象
-- 表操作
show tables;
desc 表名; # 查询表结构
show create table 表名; # 查询指定表的建表语句
create table 表名(字段 字段类型,字段 字段类型)[comment 表注释];
-- 修改表名:rename
alter table 表 rename to 新表名; # to可以省略
rename table 原表名 to 现表名;
-- 删除表
drop table 表名 (if exists); # 删除表 (一般不删表)
truncate table 表名; # 清除表中的记录
字段对象
-- 添加表字段:add column
alter table 表 add column 新字段 字段类型;
alter table 表 add constraint 自定义名字 primary key(id);
alter table 表 add primary key(id); # 给id添加主键
alter table 表 add unique(座位); # 添加唯一建约束
alter table 表 add foreign key(id) references 外表(id); # 添加外键
-- 删除字段:drop column
alter table 表 drop column 字段;
alter table 表 drop primary key; # 删除表中主键
alter table 表 drop foreign key; # 删除表中外键
-- 修改字段类型,约束等:modify column
alter table 表 modify column 字段 修改类型;
alter table 表 modify column id int not null; # 修改成非空约束
alter table 表 modify column age int default 18; # 默认18岁
alter table 表 modify column id int primary key; # id修改为主键
alter table 表 modify column id int primary key auto_increment; # 主键标识列
-- 修改字段名:change
alter table 表 change column 字段 新字段名 新的类型;
-
DML操作
Data Manipulation Language数据操作语言,用来对数据库表中的数据进行增删改。
增加 insert
insert into 表名(字段1,字段2,...) values(值1,值2,...);
修改 update
update 表名 set 字段1=值1, 字段2=值2,...[where 条件];
删除 delete
delete from 表名 [where 条件];
注:删除操作注意事项
-
当不再需要该表时,使用 DROP TABLE;
-
当仍要保留该表,只是想删除所有记录时,使用 TRUNCATE TABLE;
-
当只要删除某一行时用DELETE FROM 表名 (WHERE 某一行)
-
DQL查询
Data Query Language数据查询语言,用来查询数据库中表的记录。
/*
DISTINCT 去除重复记录
聚合函数:max、min、avg、sum、count等
*/
SELECT 字段1[AS 别名1],字段2[AS 别名2]... FROM 表名
WHERE 条件 # 条件查询(分组之前过滤)
GROUP BY 分组字段
HAVING 分组后过滤条件 # 分组查询
/*
ASC:升序(默认值)
DESC:降序
*/
ORDER BY 字段1 排序方式 # 排序查询
LIMIT 起始索引,查询记录数; # 分页查询
注:where 和 having 的区别
执行时机不同:where 是分组之前进行过滤,不满足where条件,不参与分组;而having是分组之后对结果进行过滤。
判断条件不同:where不能对聚合函数进行判断,而having可以。
执行顺序:where > 聚合函数 >having;
注:null值不参与所有聚合运算
注:运算计算符
- IS NULL
- <> 或 != -- 不等于
- between..and..
- in(...) -- 在in之后的列表中的值,多选一,满足其一即可
- like '占位符' -- 模糊匹配('-'匹配单个字符,'%'匹配任意个字符)
-
DCL控制
Data Control Language数据控制语言,用来创建数据库用户、控制数据库的访问权限 。
-- 查询用户
use mysql;
select * from user;
-- 创建用户
create user '用户名'@'主机名' identified by '密码';
-- 修改用户密码
alter user '用户名'@'主机名' identified with mysql_native_password by '密码';
-- 删除用户
drop user '用户名'@'主机名';
-- 权限控制
show grants for '用户名'@'主机名'; -- 查询权限
grant 权限列表 on 数据库.表名 to '用户名'@'主机名'; -- 授予权限
revoke 权限列表 on 数据库.表名 from '用户名'@'主机名'; -- 撤销权限
revoke all on itcast.* from 'heima'@'%';