mysql 索引 簡書 MySQL 基礎之索引

2021-10-22 04:51:00 字數 2239 閱讀 7574

mysql 索引

索引索引用於快速查詢具有特定列值的行。如果沒有索引,mysql必須從第一行開始,然後讀取整個表以查詢相關行。表越大,成本越高。如果表中有相關​​列的索引,mysql可以快速確定要在資料檔案中間尋找的位置,而無需檢視所有資料。這比按順序讀取每一行要快得多。

類似於字典中的目錄,查詢字典內容時可以根據目錄查詢到資料的存放位置,然後直接獲取即可。

本質上是告訴資料庫的儲存引擎如何快速找到我們所要的資料。所以 mysql 的索引是在 mysql 的儲存引擎層實現的,而不是在其伺服器層實現。

mysql中常見索引有:

普通索引

唯一索引

主鍵索引

組合索引

普通索引

普通索引僅有乙個功能:加速查詢

/建立表的同時建立索引/

create table t1(

id int not null auto_increment primary key,

name varchar(32),

email varchar(64),

extra text,

index ix_name(name)

/新增索引到列名 name, 索引名為 ix_name/

/單獨建立索引/

create index index_name on 表名稱(列名稱)

/example/

create index index_name on student(name);

/檢視索引/

show index from 表名稱;

/example/

show index from student;

/刪除索引/

drop index index_name on 表名稱;

/example/

drop index index_name on student;

唯一索引

唯一索引有兩個功能:加速查詢 和 唯一約束(可含null)

/建立表和唯一索引/

create table t2(

id int not null auto_increment primary key,

name varchar(32),

email varchar(64),

unique index ix_name (name)

/建立唯一索引/

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

/刪除唯一索引/

alter table student2 drop index email;

主鍵索引

主鍵有兩個功能:加速查詢 和 唯一約束(不可含null)

當乙個列被建立為主鍵是,它就會被賦予主機索引的屬性。

/建立表和建立主鍵/

create table t3(

id int ,

name varchar(32) ,

email varchar(64) ,

primary key(name)

組合索引

組合索引是將n個列組合成乙個索引

其應用場景為:頻繁的同時使用 n 個列來進行查詢,如:where name = 'shark' and age = 18。

create table studens(

id int not null auto_increment primary key,

name varchar(32) not null,

age int not null,

create index idx_name_age on students(name,age);

如上建立組合索引之後,查詢:

name and age -- 使用索引 where name='shark' and age=18;

name -- 使用索引 where name='shark';

對於多列索引的使用上需要注意, where 自己的第乙個條件的列名必須是組合索引列的最左邊的那個。

下面是可以有效使用的方式

where name='shark';

where name='shark' and age>18;

where name = 'shark' and (age >18 or age = 10);

但是不能是下面的用法

where age = 18;

where name='shark' or age=19;

注意:對於同時搜尋n個條件時,組合索引的效能好於多個單一索引合併。

mysql 索引 簡書 MySQL 索引

簡介 索引用於快速找出在某個列中有一特定值的行,不使用索引,mysql必須從第一條記錄開始讀完整個表,直到找出相關的行,表越大,查詢資料所花費的時間就越多。如果表中查詢的列有乙個索引,mysql能夠快速到達乙個位置去搜尋資料檔案,而不必檢視所有資料,那麼將會節省很大一部分時間。使用原則 索引底層使用...

mysql索引詳細介紹簡書 Mysql索引介紹

資料庫索引,是資料庫管理系統中乙個排序的資料結構,以協助快速查詢 更新資料庫表中資料。索引的實現通常使用b樹及其變種b 樹。在資料之外,資料庫系統還維護著滿足特定查詢演算法的資料結構,這些資料結構以某種方式引用 指向 資料,這樣就可以在這些資料結構上實現高階查詢演算法。這種資料結構,就是索引。為表設...

mysql 覆蓋索引 簡書 覆蓋索引

覆蓋索引 1 當發起乙個被索引覆蓋的查詢時,在explain的extra列可以看到using index的資訊,此時就使用了覆蓋索引 mysql explain select store id,film id from inventory g 1.row id 1 select type table...