MySQL優化 索引

2021-08-20 21:45:48 字數 2586 閱讀 3509

檢視資料庫索引使用的情況

handler_read_key:這個值越高越好,越高表時使用索引查詢到的次數。

handler/-read/-rnd_next:這個值越高,說明查詢低效。

四種索引(主鍵索引/唯一索引/全文索引/普通索引)

為什麼建立索引後,速度會變快?

二叉樹演算法

1.新增索引

1.1主鍵索引新增

當一張表,吧某一列設為主鍵的時候,則該列就是主鍵索引

create table aaa(

id int unsigned primary key auto_increment,

name varchar(32) not null default'');

這裡id列就是主鍵索引

當你建立表時,沒有指定主鍵索引,也可以再建立表後,再新增,指令:

alter table 表名 add primary key(列名);
舉例:

create table bbb(

id int,

name varchar(32) not null default '');

alter table bbb add primary key (id);

1.2普通索引

一般來說,普通索引的建立,是先建立表,然後在建立普通索引

比如:

create table ccc(

id int unsigned,

name vrchar(32));

create index 索引名 on 表(列)

1.3全文索引

全文索引,主要是針對對檔案,文字的檢索,比如文章。

全文索引僅針對(myisam有用),且僅對英文生效(可通過sphinx(coreseek)技術處理中文)

create table articles(

id int unsigned auto_increment not null primary key,

title varchar(200),

body text,

fulltext(title,body)

)engine=myisam charset utf8;

如何使用全文索引:

錯誤用法:select * from articles where body like '%mysql%';【不會使用全文索引】

證明:explain select * from articles where body like '%mysql%';

正確用法:

select * from articles where match(title,body) against('database');【可以】

1.4唯一索引

當表的某列被指定為unique約束時,這列就是乙個唯一索引

create table ddd(

id int primary key auto_increment,

name varchar(32) unique);

這時,name列就是乙個唯一索引

create unique index 索引名 on 表名(列名)
unique欄位可以為null且能有多個,但是如果是具體內容,則不能重複

主鍵字段不能為null,也不能重複

也可以在表建立後,通過如下語句建立唯一索引

create table eee(

id int primary key auto_increment,

name varchar(32));

create unique index 索引名 on 表名(列名)

alter table 表名 add unique 列名
2.查詢索引

desc 表名 【該方法的缺點是 不能夠顯示索引名】

show index[es] from 表名 [/g]

show keys from 表名

3.刪除索引

alter table 表名 drop index 索引名;

alter table 表名 drop primary key
4.修改

先刪除,再重新建立

mysql 優化 聚集索引 mysql 索引優化

一.聚集索引 clustered index innodb預設依據主鍵列聚集,myisam不使用 特點 b樹每個葉子包含實際資料行,資料按照索引順序地儲存在物理頁上。優點 1.範圍查詢,獲取指定id的全部資料只需從磁碟讀取少量資料頁 如果不使用聚集索引,每條資料可能引起一次磁碟io。2.由於索引和資...

mysql索引優化原則 MySQL 索引優化原則

索引優化原則 1 最左字首匹配原則,聯合索引,mysql會從做向右匹配直到遇到範圍查詢 3 and d 4 如果建立 a,b,c,d 順序的索引,d是用不到索引的,如果建立 a,b,d,c 的索引則都可以用到,a,b,d的順序可以任意調整。2 和in可以亂序,比如a 1 and b 2 and c ...

mysql索引優化原則 MySQL索引優化

mysql官方對索引的定義 索引是幫助mysql高效獲取資料的資料結構。索引是在儲存引擎中實現的,所以每種儲存引擎中的索引都不一樣。如myisam和innodb儲存引擎只支援btree索引 memory和heap儲存引擎可以支援hash和btree索引。這裡僅針對常用的innodb儲存引擎所支援的b...