sql优化主要是在优化索引,提高查询速度,那么索引分为单值索引(单列作为索引列,一个表可以有多个单值索引)、唯一索引(即字段必须是唯一值,不允许有重复值)、复合索引(多个列组合索引就像,二级目录从左边条件查起)
创建索引方式一
单值索引:create 索引类型 索引名 on 表 (索引字段)例(学生表student,以学号no为索引):
create index stu_index on student (no);
即创建名字为stu_index的索引类型为index的以no为索引的学生表索引
唯一索引:create unique index 索引名 on 表 (字段)例(学生表student以id为唯一索引)
create unique index stu_only on student (id)
复合索引:create 索引类型 索引名 on 表(多个字段/自动将多个字段作为复合索引)例(学生表以名字和年龄为复合索引)
create index stu_morer on student (name,age)
创建索引方式二
单值索引:alter table 表 add 索引类型 索引名(字段)例
alter table student add index stu_index(name)
唯一索引:alter table 表 add unique 索引类型 索引名(字段)
alter table student add unique index stu_only (id)
复合索引:alter table 表 add 索引类型 索引名 (多个字段)
alter table student add index stu_more (name,age)
删除索引:
drop index 索引名 on 表名;例(删除学生表的stu_index索引)
drop index stu_index on student;
查询索引:
show index from 表名;例如(查询学生表student都有哪些索引)
show index from student;
补充点番外知识,数据库DML\DDL操作区别
DML:包括select、update、insert、delete等操作,主要是对数据做出改变,属于事务操作,需要commit提交
DDL:包括create、alter、drop等操作,主要是对数据库的表做改变,无需commit提交,系统会自动执行