湖北专升本MySQL复习(MySQL数据库实用教程)——索引和视图

索引

根据索引的存储结构不同将其分为两类:聚簇索引和非聚簇索引。

主键索引也被称为聚簇索引,纯主键索引外其他索引称为非聚簇索引。


主键索引:为数据表中的主键字段创建一个索引,这个索引就是所谓的“主索引”。主索引区别是:在定义时使用的关键字是primary key 而不是 unique。

唯一索引:unique index;索引的字段必须是唯一,但允许有空值(注意和主键不同。


创建索引

方法一:在创建表的同时创建索引,语法格式:

create table 表名(

字段名1 数据类型 [约束条件],
...
[其他约束条件]
...
[unique | fulltext] index [索引名](字段名[(长度)][ASC | DESC])
);engine=存储类型

unique唯一索引
fulltext全文索引
create table book1(
bianhao char(20) primary key,
name char(20) not null,
jianjie text not null,
price decimal(5,2),
publish_time date not null,
unique index bianhao_unique(bianhao),
index name_index(name(20)),
fulltext index jianjie_fulltext(name,jianjie),
index complex_index(price,publish_time)
);engine=myisam

方法二:在已存在的表上创建索引

语法格式一:
create [unique | fulltext] index 索引名 on 表名(字段名 [asc|desc]);
语法格式二:
alter table 表名 add[unique | fulltext] index 索引名(字段名 [asc|desc]);
alter table book1 add fulltext index b1(jianjie);

删除索引:drop index 索引名 on 表名;

drop index complex_index on book1;

视图

 1.1创建视图(view)

视图保存仅仅是一条select语句,而select语句中的数据源可以是基表,也可以是另一个视图。

create view 视图名[(视图字段列表)]
as
select 语句;

select语句:可以是任意复杂的select语句,但通常不允许含有order by语句和distinct语句。

create view view1(学号,姓名,性别)
as
select 学号,姓名,性别 from student;
select 学号,姓名 from view1 where 性别='女';

1.2 使用视图更新数据

1)使用视图修改数据

update view1 set 姓名='东方不败' where 学号='1906010849';

2)使用视图删除数据

delete from <视图名> where <查询条件>;

delete from view1 where 学号='1906010849';

3)使用视图插入数据

insert into <视图名称> values('值','值',..

create view choose_view as select * from choose where 成绩<50;

insert into choose_view values('190601080','1',40,now());

insert into choose_view values('1906010824','4',60,now());

select * from choose;

1.3 检查视图

语法格式:create view 视图名[(视图字段)]

as

select 语句

with [ local | cascaded] check option;

local 只检查当前视图中的条件

cascaded不仅检查当前视图的条件还要检查上一级的条件

create view choose_view1
as
select * from choose where 成绩<60
with cascaded check option;

insert into choose_view1 values('1906080035','3',90,now());
insert into choose_view1 values('1906080035','4',30,now());

1.4查看视图的定义

1)show create view 视图名称;

2)视图是一个虚表,可以查看表结构的方式查看视图的定义,如: desc view1;

3)show tables 命令不仅可以显示当前数据库中所有的数据表,也可以显示数据库中所有的视图

4)MySQL系统数据库information_schema的views存储了所有视图的定义,使用以下的select语句查询该表的所有记录,也可以查看所有视图的详细信息。

select * from information_schema.views\g;

1.5 删除视图

drop view 视图名;

猜你喜欢

转载自blog.csdn.net/m0_52475160/article/details/125004071