索引,是資料庫中專門用於幫助用戶快速查詢數據的一種數據結構。類似於字典中的目錄,查找字典內容時可以根據目錄查找到數據的存放位置,然後直接獲取即可。 以 B-tree 形式存儲: MySQL中常見索引有: 普通索引 唯一索引 主鍵索引 組合索引 1、普通索引 普通索引僅有一個功能:加速查詢 1 cre ...
索引,是資料庫中專門用於幫助用戶快速查詢數據的一種數據結構。類似於字典中的目錄,查找字典內容時可以根據目錄查找到數據的存放位置,然後直接獲取即可。
以 B-tree 形式存儲:
1 30
2
3 10 40
4
5 5 15 35 66
6
7 1 6 11 19 21 39 55 100
MySQL中常見索引有:
- 普通索引
- 唯一索引
- 主鍵索引
- 組合索引
1、普通索引
普通索引僅有一個功能:加速查詢
1 create table in1(
2 nid int not null auto_increment primary key,
3 name varchar(32) not null,
4 email varchar(64) not null,
5 extra text,
6 index ix_name (name)
7 )
創建表 + 索引
1 create index index_name on table_name(column_name)
創建索引
1 drop index_name on table_name;
刪除索引
1 show index from table_name;
查看索引
註意:對於創建索引時如果是BLOB 和 TEXT 類型,必須指定length。
1 create index ix_extra on in1(extra(32));
View Code
2、唯一索引
唯一索引有兩個功能:加速查詢 和 唯一約束(可含null)
1 create table in1(
2 nid int not null auto_increment primary key,
3 name varchar(32) not null,
4 email varchar(64) not null,
5 extra text,
6 unique ix_name (name)
7 )
創建表 + 唯一索引
1 create unique index 索引名 on 表名(列名);
創建唯一索引
1 drop unique index 索引名 on 表名;
刪除唯一索引
3、主鍵索引
主鍵有兩個功能:加速查詢 和 唯一約束(不可含null)
1 create table in1(
2 nid int not null auto_increment primary key,
3 name varchar(32) not null,
4 email varchar(64) not null,
5 extra text,
6 index ix_name (name)
7 )
8
9 OR
10
11 create table in1(
12 nid int not null auto_increment,
13 name varchar(32) not null,
14 email varchar(64) not null,
15 extra text,
16 primary key(ni1),
17 index ix_name (name)
18 )
創建表 + 創建主鍵
1 alter table 表名 add primary key(列名);
創建主鍵
1 alter table 表名 drop primary key;
2 alter table 表名 modify 列名 int, drop primary key;
刪除主鍵
4、組合索引
組合索引是將n個列組合成一個索引
其應用場景為:頻繁的同時使用n列來進行查詢,如:where n1 = 'alex' and n2 = 666。
1 create table in3(
2 nid int not null auto_increment primary key,
3 name varchar(32) not null,
4 email varchar(64) not null,
5 extra text
6 )
創建表
1 create index ix_name_email on in3(name,email);
創建組合索引
如上創建組合索引之後,查詢(最左首碼):
- name and email -- 使用索引
- name -- 使用索引
- email -- 不使用索引
註意:對於同時搜索n個條件時,組合索引的性能好於多個單一索引合併。
補充
1、覆蓋索引
select * from tb where nid=1;
# 先去索引中找
# 再去數據中找
select nid from tb where nid<10;
# 先去索引中找(只需要在索引表中就能獲取到數據)
# 該情況應用上索引,並且不用去數據表中操作,即覆蓋索引。
2、合併索引(根據業務需求決定)