MySQL中索引使用简例

版权声明:本文为博主原创文章,未经允许不得转载 https://blog.csdn.net/qq_38545819/article/details/85934500

索引

  1. 一张表最多不超过4个索引
  2. 某个字段的值离散度越高,该字段越适合做索引的关键字。
  3. 占用储存空间少的字段更适合选做索引的关键字。
  4. 较频繁的作为where查询条件的字段应该创建索引,分组字段或者排序字段应该创建索引,两个表的连接字段应该创建索引。
  5. 更新频繁的字段不适合做索引,不会出现在where中的字段不应该创建索引。
  6. 最左前缀原则:
index(id,name,age)
查询id='' name='' age='' 会使用索引
id='' name='' 不会
id='' age='' 不会,必须从左至右
  1. 尽量使用前缀索引

全文索引fulltext只有在MySAM引擎中有效

show index from 表名;

查看表中的索引。

注意:在指定主键的时候,数据库会自动在主键字段上创立主键索引.

建表时创建索引语法:
create table 表名(
字段名1 数据类型 [约束条件],
…
[其他约束条件],
…
[ unique | fulltext ] index [索引名] ( 字段
名 [(长度)] [ asc | desc ] )
) engine=存储引擎类型 default charset=
字符集类型.

实例:

create table book(
isbn char(20) primary key,
name char(100) not null,
brief_introduction text not null,
price decimal(6,2),
publish_time date not null,
unique index isbn_unique (isbn),
index name_index (name (20)),
fulltext index brief_fulltext
(name,brief_introduction),
index complex_index (price,publish_time)
) engine=MyISAM default charset=gbk;
在已有表上创建索引:
语法格式⼀:
create [ unique | fulltext ] index 索引名 on 表名 ( 字段
名 [(长度)] [ asc | desc ] )
语法格式⼆:
alter table 表名 add [ unique | fulltext ] index 索引名
( 字段名 [(长度)] [ asc | desc ] )

实例:

create unique index name_index on studentinfo(name(3));

使用索引的格式:
select studentid,score
from score use index(索引名)
where studentid>=3;

select studentid,score
from score use index(index_stuid)
where studentid>=3;
在其他字段上创建的索引,但查询的studentid上没有,在查询的时候调用其他字段的索引

删除索引:

drop index 索引名 on 表名;

视图

create view ppcourse4
as 
select 
	fir.cno,fir.cname as c1,third.cname as c2
from 
	course fir,course sec,course third
where 
	fir.cpno = sec.cno
and 
	sec.cpno = third.cno


select * from ppcourse4


ppcourse4

delete from ppcourse4

drop view ppcourse4

猜你喜欢

转载自blog.csdn.net/qq_38545819/article/details/85934500