数据库优化 学习笔记
一、增加数据
连接数据库,并创建 students 表和 classes 表
-- 创建students表(id、name、age、high、gender、cls_id)
create table students(
id int not null primary key auto_increment,
name varchar(30),
age tinyint unsigned default 18,
high decimal(5,2),
gender enum('男','女','保密') default '保密', -- 存数据的时候, 只能存 '男' 或 '女''
cls_id int
);
-- 创建classes表(id、name)
create table classes(
id int primary key not null auto_increment,
name varchar(30)
);
1.1、全列插入
-- insert [into] 表名 values(...)
-- 向classes表中插入 一个班级 id name
insert into classes values(1,'一班');
-- 向students表插入 一个学生信息
-- 主键字段设置了自增约束可以不传值,用 0, null, default 来占位
insert into students values(0,'张三',18,'男',1,'2001-1-1');
insert into students values(null,'李四',19,'男',1,'2000-1-1');
insert into students values(default,'王五',19,'男',1,'2000-1-1');
1.2、枚举类型插入
-- 下标是从 1 开始的
insert into students values(default,'赵六',19,1,1,'2000-1-1');
1.3、部分插入
-- insert into 表名(列1,...) values(值1,...) -- 非空字段
insert into students(`gender`) values(2);
insert into students(`name`,`gender`) values('juran',2);
1.4、多行插入
-- 每行数据间用 , 隔开
insert into students values(default,'juran',19,'男',1,'1990-1-1'),
(default,'666',20,'男',1,'1990-1-1');
二、修改数据
2.1、修改表中某字段的全部值
-- update 表名 set 列1=值1[,列2=值2,...];
-- 名字都改成钢铁侠
update students set name='钢铁侠';
2.2、修改表中符合条件的记录的某字段
-- update 表名 set 列1=值1[,列2=值2...] where 条件;
-- 修改 id为2的记录的名字 改成钢铁侠
update students set name='钢铁侠' where id=2;
三、删除
3.1、物理删除
数据被删除后,在表中就看不到了。
-- delete from 表名 where 条件
delete from demo1; -- 没有where 就是删除整个表的数据
delete from demo1 where id = 12; -- 有 where 就是删除某条指定记录的数据
3.2、逻辑删除(因为数据很宝贵,所以一般不会真的删了)
可以理解为 “伪删除”,其实就是在表中加一个字段来表示数据是否被删除的 “状态”。如,“0” 表示是没有删除,“1” 表示数据是已经删除了不用了的。
-- 添加字段 is_delete, 表示 "是否删除". 1 删除 0 未删除
-- 查找 select * from students where is_delete=0;
-- 修改
update students set is_delete=1 where id=6;
四、查询
完整的查询语句:
select 去重选项 字段列表[as 字段名] from 数据表
where [group by 子句] [having子句] [order by 子句] [limit子句];
先写前半句几个简单的,剩下半句,后面再补充。
4.1、查询所有字段
select * from students;
4.2、去除重复字段的查询
-- distinct 判断的是整条记录是否重复
select distinct * from students;
select distinct name from students;
select distinct name,age from students;
4.3、查询指定字段
-- select 列1[,列2,...] from 表名;
select name,age,gender from students;
4.4、可以使用 as 为字段或表指定别名
select name as n from students where n='张三'; -- 会报错, 因为其修改是并不是表的字段名, 而是结果的显示名
select name as n,gender from students where name='张三'; -- 要这样写
select s.name,s.gender from students as s; -- 指定表的别名(一般是多表联合查询时才会用到)