Mysql第五章索引和视图
一.索引
1.相当于书的目录,加快查询速度
2.索引添加在字段上,建在经常where条件中使用的字段上(如,查询学生姓名where name=’xx’,可以在name创建索引)
3.创建索引能加快查询速度,但是耗费系统空间,因为需要很大一块空间来存放索引
4.经常插入修改数据的表,不建议创建索引,索引会降低插入和修改的效率
查看索引:
show index from student;
二.索引分类
1.普通索引
创建普通索引:
create index name_index on student(s_name);
删除索引:
alter table student drop index name_index;
2.唯一索引
如果创建了主键,唯一,外键约束,那就会自动创建主键索引,唯一索引,外键索引
创建唯一索引:
create unique index uq_index_no on student(s_no);
3.组合索引
创建组合索引(适合多列子查询):
create index index_no_name on student(s_no,s_name);
三.视图
1.它是一张虚拟的表,基于select查询
2.简化复杂的查询(对非常复杂的查询创建视图,下次直接查询视图即可)
3.可以做权限控制,屏蔽掉一些敏感的字段
基于复杂的sql创建视图:
create view first_view as
select sb_name,s_name,score from student s,result r,subject sb where s.s_no=r.s_no and r.sb_no=
sb.sb_no and (sb_name,score) in (select sb_name,max(score) from result r,subject sb where
r.sb_no=sb.sb_no group by sb_name);
基于原表创建视图(修改视图数据会影响原表数据):
create view stu_view as
select s_no,s_name,s_sex,c_no from student;
查询视图就跟普通表一样:
select * from first_view where sb_name='JAVA';
修改视图:
alter view stu_view as select s_no,s_name,s_sex from student;
删除视图:
drop view stu_view;
详细课程查询:
Mysql系列课程–第一章 Sql分类 常用命令
Mysql系列课程–第二章 约束 自增主键
Mysql系列课程–第三章 建表 插数据
Mysql系列课程–第四章 备份 普通查询
Mysql系列课程–第五章 高级查询 表连接 子查询 case when
Mysql系列课程–第六章 索引和视图
Mysql系列课程–第七章 触发器和存储过程
Mysql系列课程–第八章 sql精选35道题