DDL
1. 创建数据库
Create database 库名;
Drop database 库名;
2. 创建表
Create table 表名(列名列的数据类型 约束条件, … , … );
数值:int 整型 float 浮点型
文本:char/varchar
日期:date
Primary key 主键
Foreign key 外键
Not null 非空
Unique 唯一
3. 修改表
a.修改名称:rename table 旧表名 to 新表名;
b.修改字段名称:alter table 表名 change 旧字段 新字段 数据类型;
c.修改字段的数据类型:alter table 表名 modify 字段 数据类型;
d.删除字段:alter table 表名 drop 字段1,drop字段2;
f.增加字段:alter table 表名 add 字段名 数据类型 约束条件;
4. 删除表: Drop table 表名;
DML
1. 增加数据
Insert into表名(字段)values (值);
Insert into 表名(字段1,字段2)values(字段值1,字段值2);
2. 删除数据
Detele from 表名 (where子句);
Truncate table 表名;
3. 修改数据
Update 表名 set 字段=值(where子句);
4. 查询数据
子句:
where 子句——过滤行
a. 比较运算符
< > >= <= =
Between … and…显示在某一区间的值
In(set) 显示在in列表中的值
Like ‘_a’ / ’a%’ 模糊查询,% 代表零个或多个任意字符,_代表一个字符
Is null 判断是否为空
b. 逻辑运算符
And 多个条件同时成立
Or 多个条件任一成立
Not 不成立,例:where not(salary>100);
c. 聚合函数
统计行数-count()
求和-sum()
求平均值-avg()
求最大、最小-max()/min()
d. 针对字段去重:distinct(字段)
group by 子句——分组(列)
having 子句——在group by后进行过滤,必须跟在groupby使用不可单独使用
order by 子句——列排序 默认asc 升序,desc 降序
limit 初始位置,记录数; (分页)
A. 单表查询
Select 字段 from 表名;
B. 多表查询: 涉及多表,表与表之间通过相关字段(主外键),产生关系
select 字段 from 表1,表2,...where 表1.字段=表2.字段;
C. 子查询(嵌套查询)
select 字段 from 表(select 字段 from 表)
where (select语句);
D. 合并查询
union/union all
E. 左右连接
left join...on../right join...on...
select 字段 from 表1 left join 表2 on 表1.字段=表2.字段;
DCL
1. 索引:提高查询速度
Create index 索引名 on 表(字段,字段…)
2. 视图:提高数据安全性
Create view 视图名 as select 语句;
3. 触发器
Create trigger 触发名 before/after Inset/update/delete on 表名
For each row
Begin
Sql语句;
End;
4. 存储过程 (循环体+判断语句)批量操作
Delimiter$$
Create procedure 储存名(in 参数名 参数类型)
Begin
qq : loop
seta=a+1;
if a<10 then sql语句;
else leave qq;
endif;
end;$$
delimiter;