数据库基本操作
关系型数据库: 以二维表存储数据
数据表操作
- 数据表的创建
1 | -- unsigned: 无符号 |
- 数据表的删除
1 |
|
数据操作
- 增
1 | -- 单条添加 |
- 删
1 | -- 删除表中所有数据 |
- 改
1 | update demo set name = "小乔", age = 20 where id = 10; |
- 查
1 |
|
- 去掉字段中重复的数据
1 | select distinct sex from student; |
- 排序
1 | select * from student order by age; |
聚合函数
- count 统计
1 | select count(*) from student; ==> 只要有值就统计 |
- max 最大值
1 | select max(age) from student; |
- min 最小值
1 | select min(age) from student; |
- sum 求和
1 | select sum(age) from student; |
- avg 平均值
1 | select avg(age) from student; |
分组
- group by 根据某一字段排序,可以去重
1 | -- 每个班级的平均,最大年龄 |
连接查询
- 等值查询
1 | select * from student as stu, score as sc where stu.sid = sc.sid; |
- 内查询
1 | select * from student as stu |
- 多表连接(两两之间产生条件)
1 | select * from student as stu |
- 自关联(同一个表查询多次,自己产生关联,表必须起别名)
1 | select * from areas as sheng |
- 左连接(jion 前边的表)
1 | select * from student as stu |
- 右连接
1 | select * from student as stu |
- 子查询
1 | -- 查询大于平均年龄的学生 |
- 数据分表
1 | create table newStudent ( |
索引(作用于某个字段)
加索引后会使写入、修改、删除变慢,每一次增加数据平衡树都会重新排列,也会增加表的体积,占用磁盘存储空间。
- 查看索引
1 | show index from 表名; |
- 创建索引(创建索引后,表在磁盘上的存储结构就由整齐排列的结构转变成了树状结构,也就是「平衡树」结构)
1 | -- 建表时创建索引 key (age)、primary key、unique |
表的备份
1 | CREATE TABLE PPI_SYS_CFG_bk_20200810 as select * from PPI_SYS_CFG |