首頁技術(shù)文章正文

mysql索引如何使用?

更新時間:2020-02-24 來源:黑馬程序員 瀏覽量:

 1、為什么要學(xué)索引

思考:在一本字典中,如何查找一個字?

分析: 一般的應(yīng)用系統(tǒng)對比數(shù)據(jù)庫的讀寫比例在10:1左右,而且插入操作和更新操作很少出現(xiàn)性能問題,遇到最多的,也是最容易出問題的,還是一些復(fù)雜的查詢操作,所以查詢語句的優(yōu)化顯然是重中之重。

2、 什么是索引

索引相當(dāng)于目錄結(jié)構(gòu),其內(nèi)部有一定的算法,可以快速的幫我們定位到,相應(yīng)的數(shù)據(jù)位置


3、索引的好處

當(dāng)數(shù)據(jù)比較多的時候可以加快查詢的速度.


4、使用索引的原則

可以打開京東頁面

在經(jīng)常需要搜索的列上,可以加快搜索的速度;

在經(jīng)常用在連接的列上,這些列主要是一些外鍵,可以加快連接的速度;

在經(jīng)常需要排序的列上創(chuàng)建索引,因為索引已經(jīng)排序,這樣查詢可以 利用索引的排序,加快排序查詢時間;

在經(jīng)常使用在WHERE子句中的列上面創(chuàng)建索引,加快條件的判斷速度。

5、索引的類型

primary key  主鍵索引保證數(shù)據(jù)的唯一性,而且不能為空,唯一標(biāo)識數(shù)據(jù)庫表中的每條記錄

unique       唯一索引  防止數(shù)據(jù)出現(xiàn)重復(fù)

index(key)   普通索引   僅僅只是為了提高查詢的速度

fulltext      全文索引(不支持中文)

6、索引的使用

(1)建表的時候創(chuàng)建索引

create table study(

id mediumint not null auto_increment,

sn char(10) not null default 0 comment '學(xué)號',

xing varchar(10) not null default '' comment '姓',

ming varchar(10) not null default '' comment '名',

primary key(id),

unique sn(sn),

 index x_m(xing,ming)

)engine=MyISAM default charset=utf8;


1582535620111_mysql索引01.jpg


查看創(chuàng)建成功的表的結(jié)構(gòu)

show create table study \G

1582535631414_mysql索引02.jpg


使用desc查看表的結(jié)構(gòu)

1582535642052_mysql索引03.jpg

除了主鍵索引,其他索引設(shè)置的同時可以給其起一個”名稱”,名稱不設(shè)置與該索引字段名稱一致

給存在的數(shù)據(jù)表增加索引

alter table 表名 add   primary key (id);

alter table 表名 add   unique key [索引名稱]   (字段);

alter table 表名 add   key  [索引名稱]   (字段);

alter table 表名 add   fulltext key  [索引名稱]   (字段);

這里的索引名稱都是可以不寫的,那么默認(rèn)就是字段的名稱。

a 先添加一張表

create table study1(

id mediumint not  null,

sn  char(10) not null default 0 comment '學(xué)號',

xing  varchar(10) not null default '' comment '姓',

ming  varchar(10) not null default '' comment '名'

)engine=myisam default  charset='utf8';


1582535655667_mysql索引04.jpg

b 為已經(jīng)創(chuàng)建好的表增加索引

alter table study1 add primary key(id);   // 主鍵索引

alter table study1 add unique sn(sn);     // 給學(xué)號增加唯一索引

alter table study1 add index x_m(xing,ming);  // 給xingming添加

復(fù)合索引

1582535667116_mysql索引06.jpg

c 查看已經(jīng)建立好的索引:

1582535676868_mysql索引07.jpg


猜你喜歡

MySQL數(shù)據(jù)庫安裝教程詳解

windows系統(tǒng)怎么登錄MySQL數(shù)據(jù)庫?


分享到:
在線咨詢 我要報名
和我們在線交談!