最全面的 MySQL 索引详解
本文章來自?http://www.codeceo.com/article/mysql-index-2.html
?
什么是索引?
1、索引
索引是表的目錄,在查找內(nèi)容之前可以先在目錄中查找索引位置,以此快速定位查詢數(shù)據(jù)。對(duì)于索引,會(huì)保存在額外的文件中。
2、索引,是數(shù)據(jù)庫中專門用于幫助用戶快速查詢數(shù)據(jù)的一種數(shù)據(jù)結(jié)構(gòu)。類似于字典中的目錄,查找字典內(nèi)容時(shí)可以根據(jù)目錄查找到數(shù)據(jù)的存放位置,然后直接獲取即可。
索引由數(shù)據(jù)庫中一列或多列組合而成,其作用是提高對(duì)表中數(shù)據(jù)的查詢速度
索引的優(yōu)點(diǎn)是可以提高檢索數(shù)據(jù)的速度
索引的缺點(diǎn)是創(chuàng)建和維護(hù)索引需要耗費(fèi)時(shí)間
索引可以提高查詢速度,會(huì)減慢寫入速度
索引分類
1.普通索引
2.唯一索引
3.全文索引
4.單列索引
5.多列索引
6.空間索引
7.主鍵索引
8.組合索引
- 普通索引:僅加速查詢
- 唯一索引:加速查詢 + 列值唯一(可以有null)
- 主鍵索引:加速查詢 + 列值唯一 + 表中只有一個(gè)(不可以有null)
- 組合索引:多列值組成一個(gè)索引,
專門用于組合搜索,其效率大于索引合并 - 全文索引:對(duì)文本的內(nèi)容進(jìn)行分詞,進(jìn)行搜索
索引合并,使用多個(gè)單列索引組合搜索
覆蓋索引,select的數(shù)據(jù)列只用從索引中就能夠取得,不必讀取數(shù)據(jù)行,換句話說查詢列要被所建的索引覆蓋
如何創(chuàng)建索引?記住一個(gè)單詞—explain
創(chuàng)建表的時(shí)候創(chuàng)建索引
CREATE TABLE tbl_name(字段名稱 字段類型 [完整性約束條件],,,,,[UNIQUE|FULLTEXT|SPATIAL] INDEX|KEY[索引名稱](字段名稱[(長度)]) [ASC|DESC] );在已經(jīng)存在的表上創(chuàng)建索引:
1.CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX 索引名稱 ON 表名{字段名稱[(長度)] [ASC|DESC]} 2.ALTER TABLE tbl_name ADD [UNIQUE|FULLTEXT|SPATIAL] INDEX索引名稱(字段名稱[(長度)][ASC|DESC]);如何刪除索引?
DROP INDEX 索引名稱 ON tbl_name1.普通索引
普通索引僅有一個(gè)功能:加速查詢
創(chuàng)建表+索引
create table in1(nid int not null auto_increment primary key, name varchar(32) not null, email varchar(64) not null, extra text, index ix_name (name) )創(chuàng)建索引
create index index_name on table_name(column_name)刪除索引
drop index_name on table_name;查看索引
show index from table_name;注意:對(duì)于創(chuàng)建索引時(shí)如果是BLOB?和?TEXT?類型,必須指定length。
create index ix_extra on in1(extra(32));2、唯一索引
唯一索引有兩個(gè)功能:加速查詢 和 唯一約束(可含null)
創(chuàng)建表+唯一索引
create table in1(nid int not null auto_increment primary key, name varchar(32) not null, email varchar(64) not null, extra text, unique ix_name (name) )創(chuàng)建唯一索引
create unique index 索引名 on 表名(列名)刪除唯一索引
drop unique index 索引名 on 表名3、主鍵索引
主鍵有兩個(gè)功能:加速查詢 和 唯一約束(不可含null)
創(chuàng)建表+創(chuàng)建主鍵
create table in1(nid int not null auto_increment primary key, name varchar(32) not null, email varchar(64) not null, extra text, index ix_name (name) ) OR create table in1( nid int not null auto_increment, name varchar(32) not null, email varchar(64) not null, extra text, primary key(ni1), index ix_name (name) )創(chuàng)建主鍵
alter table 表名 add primary key(列名);刪除主鍵
alter table 表名 drop primary key; alter table 表名 modify 列名 int, drop primary key;4、組合索引
組合索引是將n個(gè)列組合成一個(gè)索引
其應(yīng)用場(chǎng)景為:頻繁的同時(shí)使用n列來進(jìn)行查詢,如:where n1 = ‘a(chǎn)lex’ and n2 = 666。
創(chuàng)建表
create table in3(nid int not null auto_increment primary key, name varchar(32) not null, email varchar(64) not null, extra text )創(chuàng)建組合索引
create index ix_name_email on in3(name,email);如上創(chuàng)建組合索引之后,查詢:
- name and email ?– 使用索引
- name ? ? ? ? ? ? ? ? — 使用索引
- email ? ? ? ? ? ? ? ? — 不使用索引
注意:對(duì)于同時(shí)搜索n個(gè)條件時(shí),組合索引的性能好于多個(gè)單一索引合并。
相關(guān)命令
- 查看表結(jié)構(gòu)desc 表名- 查看生成表的SQLshow create table 表名- 查看索引show index from 表名 - 查看執(zhí)行時(shí)間 set profiling = 1; SQL... show profiles;使用索引和不使用索引
由于索引是專門用于加速搜索而生,所以加上索引之后,查詢效率會(huì)快到飛起來。# 有索引 mysql> select * from tb1 where name = 'wupeiqi-888'; +-----+-------------+---------------------+----------------------------------+---------------------+ | nid | name | email | radom | ctime | +-----+-------------+---------------------+----------------------------------+---------------------+ | 889 | wupeiqi-888 | wupeiqi888@live.com | 5312269e76a16a90b8a8301d5314204b | 2016-08-03 09:33:35 | +-----+-------------+---------------------+----------------------------------+---------------------+ 1 row in set (0.00 sec) # 無索引 mysql> select * from tb1 where email = 'wupeiqi888@live.com'; +-----+-------------+---------------------+----------------------------------+---------------------+ | nid | name | email | radom | ctime | +-----+-------------+---------------------+----------------------------------+---------------------+ | 889 | wupeiqi-888 | wupeiqi888@live.com | 5312269e76a16a90b8a8301d5314204b | 2016-08-03 09:33:35 | +-----+-------------+---------------------+----------------------------------+---------------------+ 1 row in set (1.23 sec)正確使用索引
數(shù)據(jù)庫表中添加索引后確實(shí)會(huì)讓查詢速度起飛,但前提必須是正確的使用索引來查詢,如果以錯(cuò)誤的方式使用,則即使建立索引也會(huì)不奏效。
即使建立索引,索引也不會(huì)生效:
- like '%xx'select * from tb1 where name like '%cn'; - 使用函數(shù) select * from tb1 where reverse(name) = 'wupeiqi'; - or select * from tb1 where nid = 1 or email = 'seven@live.com'; 特別的:當(dāng)or條件中有未建立索引的列才失效,以下會(huì)走索引 select * from tb1 where nid = 1 or name = 'seven'; select * from tb1 where nid = 1 or email = 'seven@live.com' and name = 'alex' - 類型不一致 如果列是字符串類型,傳入條件是必須用引號(hào)引起來,不然... select * from tb1 where name = 999; - != select * from tb1 where name != 'alex' 特別的:如果是主鍵,則還是會(huì)走索引 select * from tb1 where nid != 123 - > select * from tb1 where name > 'alex' 特別的:如果是主鍵或索引是整數(shù)類型,則還是會(huì)走索引 select * from tb1 where nid > 123 select * from tb1 where num > 123 - order by select email from tb1 order by name desc; 當(dāng)根據(jù)索引排序時(shí)候,選擇的映射如果不是索引,則不走索引 特別的:如果對(duì)主鍵排序,則還是走索引: select * from tb1 order by nid desc; - 組合索引最左前綴 如果組合索引為:(name,email) name and email -- 使用索引 name -- 使用索引 email -- 不使用索引其他注意事項(xiàng)
- 避免使用select * - count(1)或count(列) 代替 count(*) - 創(chuàng)建表時(shí)盡量時(shí) char 代替 varchar - 表的字段順序固定長度的字段優(yōu)先 - 組合索引代替多個(gè)單列索引(經(jīng)常使用多個(gè)條件查詢時(shí)) - 盡量使用短索引 - 使用連接(JOIN)來代替子查詢(Sub-Queries) - 連表時(shí)注意條件類型需一致 - 索引散列值(重復(fù)少)不適合建索引,例:性別不適合limit分頁
無論是否有索引,limit分頁是一個(gè)值得關(guān)注的問題
每頁顯示10條: 當(dāng)前 118 120, 125倒序:大 小980 970 7 6 6 5 54 43 3221 19 98 下一頁:select * from tb1 where nid < (select nid from (select nid from tb1 where nid < 當(dāng)前頁最小值 order by nid desc limit 每頁數(shù)據(jù) *【頁碼-當(dāng)前頁】) A order by A.nid asc limit 1) order by nid desc limit 10; select * from tb1 where nid < (select nid from (select nid from tb1 where nid < 970 order by nid desc limit 40) A order by A.nid asc limit 1) order by nid desc limit 10; 上一頁: select * from tb1 where nid < (select nid from (select nid from tb1 where nid > 當(dāng)前頁最大值 order by nid asc limit 每頁數(shù)據(jù) *【當(dāng)前頁-頁碼】) A order by A.nid asc limit 1) order by nid desc limit 10; select * from tb1 where nid < (select nid from (select nid from tb1 where nid > 980 order by nid asc limit 20) A order by A.nid desc limit 1) order by nid desc limit 10;
執(zhí)行計(jì)劃
explain?+ 查詢SQL – 用于顯示SQL執(zhí)行信息參數(shù),根據(jù)參考信息可以進(jìn)行SQL優(yōu)化
mysql> explain select * from tb2; +----+-------------+-------+------+---------------+------+---------+------+------+-------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+------+---------------+------+---------+------+------+-------+ | 1 | SIMPLE | tb2 | ALL | NULL | NULL | NULL | NULL | 2 | NULL | +----+-------------+-------+------+---------------+------+---------+------+------+-------+ 1 row in set (0.00 sec)執(zhí)行計(jì)劃
id查詢順序標(biāo)識(shí)如:mysql> explain select * from (select nid,name from tb1 where nid < 10) as B; +----+-------------+------------+-------+---------------+---------+---------+------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+------------+-------+---------------+---------+---------+------+------+-------------+ | 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 9 | NULL | | 2 | DERIVED | tb1 | range | PRIMARY | PRIMARY | 8 | NULL | 9 | Using where | +----+-------------+------------+-------+---------------+---------+---------+------+------+-------------+ 特別的:如果使用union連接氣值可能為null select_type 查詢類型 SIMPLE 簡單查詢 PRIMARY 最外層查詢 SUBQUERY 映射為子查詢 DERIVED 子查詢 UNION 聯(lián)合 UNION RESULT 使用聯(lián)合的結(jié)果 ... table 正在訪問的表名 type 查詢時(shí)的訪問方式,性能:all < index < range < index_merge < ref_or_null < ref < eq_ref < system/const ALL 全表掃描,對(duì)于數(shù)據(jù)表從頭到尾找一遍 select * from tb1; 特別的:如果有l(wèi)imit限制,則找到之后就不在繼續(xù)向下掃描 select * from tb1 where email = 'seven@live.com' select * from tb1 where email = 'seven@live.com' limit 1; 雖然上述兩個(gè)語句都會(huì)進(jìn)行全表掃描,第二句使用了limit,則找到一個(gè)后就不再繼續(xù)掃描。 INDEX 全索引掃描,對(duì)索引從頭到尾找一遍 select nid from tb1; RANGE 對(duì)索引列進(jìn)行范圍查找 select * from tb1 where name < 'alex'; PS: between and in > >= < <= 操作 注意:!= 和 > 符號(hào) INDEX_MERGE 合并索引,使用多個(gè)單列索引搜索 select * from tb1 where name = 'alex' or nid in (11,22,33); REF 根據(jù)索引查找一個(gè)或多個(gè)值 select * from tb1 where name = 'seven'; EQ_REF 連接時(shí)使用primary key 或 unique類型 select tb2.nid,tb1.name from tb2 left join tb1 on tb2.nid = tb1.nid; CONST 常量 表最多有一個(gè)匹配行,因?yàn)閮H有一行,在這行的列值可被優(yōu)化器剩余部分認(rèn)為是常數(shù),const表很快,因?yàn)樗鼈冎蛔x取一次。 select nid from tb1 where nid = 2 ; SYSTEM 系統(tǒng) 表僅有一行(=系統(tǒng)表)。這是const聯(lián)接類型的一個(gè)特例。 select * from (select nid from tb1 where nid = 1) as A; possible_keys 可能使用的索引 key 真實(shí)使用的 key_len MySQL中使用索引字節(jié)長度 rows mysql估計(jì)為了找到所需的行而要讀取的行數(shù) ------ 只是預(yù)估值 extra 該列包含MySQL解決查詢的詳細(xì)信息 “Using index” 此值表示mysql將使用覆蓋索引,以避免訪問表。不要把覆蓋索引和index訪問類型弄混了。 “Using where” 這意味著mysql服務(wù)器將在存儲(chǔ)引擎檢索行后再進(jìn)行過濾,許多where條件里涉及索引中的列,當(dāng)(并且如果)它讀取索引時(shí),就能被存儲(chǔ)引擎檢驗(yàn),因此不是所有帶where子句的查詢都會(huì)顯示“Using where”。有時(shí)“Using where”的出現(xiàn)就是一個(gè)暗示:查詢可受益于不同的索引。 “Using temporary” 這意味著mysql在對(duì)查詢結(jié)果排序時(shí)會(huì)使用一個(gè)臨時(shí)表。 “Using filesort” 這意味著mysql會(huì)對(duì)結(jié)果使用一個(gè)外部索引排序,而不是按索引次序從表里讀取行。mysql有兩種文件排序算法,這兩種排序方式都可以在內(nèi)存或者磁盤上完成,explain不會(huì)告訴你mysql將使用哪一種文件排序,也不會(huì)告訴你排序會(huì)在內(nèi)存里還是磁盤上完成。 “Range checked for each record(index map: N)” 這個(gè)意味著沒有好用的索引,新的索引將在聯(lián)接的每一行上重新估算,N是顯示在possible_keys列中索引的位圖,并且是冗余的。慢日志查詢
a、配置MySQL自動(dòng)記錄慢日志
slow_query_log = OFF 是否開啟慢日志記錄 long_query_time = 2 時(shí)間限制,超過此時(shí)間,則記錄 slow_query_log_file = /usr/slow.log 日志文件 log_queries_not_using_indexes = OFF 為使用索引的搜索是否記錄注:查看當(dāng)前配置信息:
? ? show variables like ‘%query%’
? ? ?修改當(dāng)前配置:
set global 變量名 = 值
b、查看MySQL慢日志
mysqldumpslow -s at -a ?/usr/local/var/mysql/MacBook-Pro-3-slow.log
參數(shù)詳解
""" --verbose 版本 --debug 調(diào)試 --help 幫助-v 版本 -d 調(diào)試模式 -s ORDER 排序方式what to sort by (al, at, ar, c, l, r, t), 'at' is defaultal: average lock time ar: average rows sent at: average query time c: count l: lock time r: rows sent t: query time -r 反轉(zhuǎn)順序,默認(rèn)文件倒序拍。reverse the sort order (largest last instead of first) -t NUM 顯示前N條just show the top n queries -a 不要將SQL中數(shù)字轉(zhuǎn)換成N,字符串轉(zhuǎn)換成S。don't abstract all numbers to N and strings to 'S' -n NUM abstract numbers with at least n digits within names -g PATTERN 正則匹配;grep: only consider stmts that include this string -h HOSTNAME mysql機(jī)器名或者IP;hostname of db server for *-slow.log filename (can be wildcard), default is '*', i.e. match all -i NAME name of server instance (if using mysql.server startup script) -l 總時(shí)間中不減去鎖定時(shí)間;don't subtract lock time from total time """轉(zhuǎn)載于:https://www.cnblogs.com/qinweizhi/p/5770273.html
總結(jié)
以上是生活随笔為你收集整理的最全面的 MySQL 索引详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网页解析的全过程(输入url到展示页面)
- 下一篇: linux cmake编译源码,linu