天天看點

11.索引的基本使用

1.簡介

索引是一種特殊的資料結構,類似于圖書的目錄,它能夠極大地提升資料庫的查詢效率。如果沒有索引,在查詢資料時必須掃描表中的所有記錄才能找出符合條件的記錄,這種全表掃描的查詢效率非常低。

2.種類

索引種類 描述
普通索引 最基本的索引,沒有任何限制,僅加速查詢
唯一索引 索引列的值必須唯一,但允許有空值
主鍵索引 一種特殊的唯一索引,不允許有空值。一般是在建表的同時自動建立主鍵索引
複合索引 兩個或多個列上的索引被稱作複合索引
全文索引 對文本内容進行分詞索引

3.使用

#建立普通索引
create index indexName on tableName(field(length));

#建立唯一索引
create unique index indexName on tableName(field(length));

#建立複合索引
create index indexName on tableName(field1, field2, …,fieldN);

#删除索引
drop index indexName on tableName;

#檢視索引
show index from tableName;      

4.複合索引前導列特性

在MySQL中,如果建立了複合索引(name, salary, dept),就相當于建立了(name, salary, dept)、(name, salary)和(name)三個索引,這被稱為複合索引前導列特性,是以在建立複合索引時應該将最常用作查詢條件的列放在最左邊,然後依次遞減。

#未使用索引
select * from employee where salary = 8800;
select * from employee where dept = '部門A';
select * from employee where salary = 8800 and dept = '部門A';

#使用索引
select * from employee where name = 'liufeng';
select * from employee where name = 'liufeng' and salary = 8800;
select * from employee where name = 'liufeng' and salary = 8800 and dept = '部門A';