MySQL的索引和视图

索引:一种特殊的文件,用来快速查询数据库表中的特定记录,避免查询时全表扫描

创建索引:

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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值