是什么
什么是索引
- 索引類(lèi)似圖書(shū)的目錄, 可以提高數(shù)據(jù)庫(kù)檢索的效率, 降低數(shù)據(jù)庫(kù)IO成本
- 索引其實(shí)就是一種排好序的數(shù)據(jù)結(jié)構(gòu)
有哪些索引
根據(jù)索引是否為主鍵分類(lèi)
- 主索引
- 主鍵索引(主索引): 非空且唯一
如果表中有主鍵: 主鍵即主索引
如果表中沒(méi)有主鍵: InnoDB會(huì)選擇一個(gè)唯一的非空索引代替, 如果沒(méi)有非空唯一索引則隱式定義一個(gè)主鍵作為主索引
-
輔助索引
- 唯一索引: 唯一, 可為空
- 普通索引: 沒(méi)有任何限制
- 全文索引: 大文本對(duì)象作為索引
5.6之前的版本中遵堵,全?文索引只能?用于MyISAM存儲(chǔ)引擎 5.6 及以后的版本,MyISAM 和 InnoDB 均?支持全?文索引 在之前的MySQL中怨规,全?文索引只對(duì)英?文有?用陌宿,?目前對(duì)中?文還不不?支持 MySQL8的版本中?支持了了對(duì)中?文分詞的全?文索引
- 組合索引: 多個(gè)列組合為一個(gè)索引, 列值非空
根據(jù)數(shù)據(jù)的存儲(chǔ)方式分類(lèi)
- 聚簇索引: 索引即數(shù)據(jù), 數(shù)據(jù)即索引 (一個(gè)索引與一條記錄存放在同一內(nèi)存塊中)
- 非聚簇索引: 索引包含創(chuàng)建索引的列值和key, 獲取其他列的值需通過(guò)key回表查詢(xún)
對(duì)于InnoDB, 主鍵索引為聚簇索引(主鍵代表了唯一數(shù)據(jù)), 輔助索引為非聚簇索引
對(duì)于MyISAM, 只有非聚簇索引, 當(dāng)找到索引后, 得到數(shù)據(jù)存在表中的行號(hào), 通過(guò)行號(hào)回表查詢(xún)數(shù)據(jù)
MyISAM和InnoDB的區(qū)別
- 數(shù)據(jù)存儲(chǔ)方式:
- InnoDB由兩種?文件組成,表結(jié)構(gòu)波丰,數(shù)據(jù)和索引
- MyISAM由三種?文件組成壳坪,表結(jié)構(gòu)、數(shù)據(jù)掰烟、索引
- 索引的方式:
- 索引的底層都是基于B+Tree的數(shù)據(jù)結(jié)構(gòu)建?
- InnoDB中主鍵索引為聚簇索引爽蝴,輔助索引是非聚簇索引
- MyISAM中數(shù)據(jù)和索引存在不同的文件中,因此都是非聚簇索引
- 事務(wù)的支持:
- InnoDB支持事務(wù)
- MyISAM不支持事務(wù)
怎么做
索引的創(chuàng)建, 修改, 刪除
主鍵索引
-- 創(chuàng)建表時(shí), 直接創(chuàng)建主鍵索引(創(chuàng)建自增主鍵)
create table users(
id int not null auto_increment primary key
)engine=innobd default charser=utf8mb4;
-- 修改時(shí)添加主鍵和自增
alter table users modify uid int primary key auto_increment;
-- 刪除主鍵索引, 注意需要先取消自增, 在刪除主鍵
alter table users modify uid int;
alter table users drop primary key;
唯一索引
-- 創(chuàng)建表時(shí), 直接創(chuàng)建唯一索引
create table users(
name vaarchar(10) not null,unique key u_name(name)
)engine=innodb default charset=utf8mb4;
-- 添加唯一索引 unique 當(dāng)前列要求唯一, 允許為空
alter table users add unique u_name(name);
-- 刪除唯一索引
alter table users drop index u_name;
普通索引
-- 創(chuàng)建表時(shí), 直接創(chuàng)建普通索引
create table users(
email varchar(10) not null,key index_email(email)
)engine=innodb default charset=utf8mb4;
-- 添加索引
alter table users add index in_name(email);
-- 刪除索引
drop index in_name on users;
全文索引
alter table 表名 add fulltext index ft_index(列名);
組合索引
-- 添加索引
alter table users add index in_x(email, phone, uname);
-- 刪除索引
alter table users drop in_x;