索引:一种特殊的文件,用来快速查询数据库表中的特定记录,避免查询时全表扫描
创建索引:
create (unique) index 索引名 on 表名(列名) (asc|desc);
alter table 表名 add index 索引名(列名);
查看索引:
show index from table_name;
show create table 表名 \G
删除索引:
drop index 索引名 on 表名
视图:一种虚拟表,内容为查询结果,不包含查询语句、
创建视图:
create view 视图名 as 视图内容 from 原始表;
更新视图:
mysql> create or replace view v_avg as
-> select sno,sname,ssex,sage from student where sage>20 with check option;
#更新视图时需要满足构建视图的条件
修改视图:
create or replace view v_student as select sno, sname, ssex, sage from
student;
alter view v_student as select sno, sname, ssex, sage from student where ssex="女";
删除视图:
drop view [if exists] 视图名;
视图和索引案例:
一、新建数据库
create database mydb15_indexstu;
use mydb15_indexstu
二、创建表
Student表:
create table Student(Sno int primary key auto_increment,Sname varchar(30) not null unique,Ssex varchar(2) check(Ssex='男' or Ssex='女') not null,Sage int not null,Sdept varchar(10) default '计算机' not null);
Course表:
create table Course(Con int primary key not null,Cname varchar(20) not null);
SC表:
create table SC(Sno int not null,Con varchar(10) primary key not null,Score int not null);
三、处理表
1.修改student 表中年龄(sage)字段属性,数据类型由int 改变为sma1lint
alter table Student change column sage sage smallint;
2. 为Course表中Cno 课程号字段设置索引,并查看索引
create index con_index on Course(Con);
3. 为SC表建立按学号(sno)和课程号(cno)组合的升序的主键索引,索引名为SC_INDEX
alter table SC add index SC_INDEX(Sno,Con asc);
4. 创建一视图 stu info,查询全体学生的姓名,性别,课程名,成绩
create view stu_info as select a.Sname,a.Ssex,b.Cname,c.Score from Student a,Course b,SC c where a.Sno=c.Sno and b.Con=c.Con;
5. 删除所有索引
drop index SC_INDEX on SC;
drop index con_index on Course;