表格創建如下:
1.創建聯合索引
ALTER table user add INDEX p_n_u(pid,name,user_no)
2.索引對應的key_len如下:
pid int(11) unsigned key_len=4
name char(32) key_len=32*3=96
user_no char(11) key_len=11*3=33
注釋:索引的key_len對應計算如下:
char和varchar類型key_len計算公式: varchr(N)變長字段且允許NULL = N * ( character set:utf8=3,gbk=2,latin1=1)+1(NULL)+2(變長字段)
varchr(N)變長字段且不允許NULL = N * ( character set:utf8=3,gbk=2,latin1=1)+2(變長字段)
char(N)固定字段且允許NULL = N * ( character set:utf8=3,gbk=2,latin1=1)+1(NULL) char(N)固定字段且不允許NULL = N * ( character set:utf8=3,gbk=2,latin1=1)
數值數據的key_len計算公式:
TINYINT允許NULL = 1 + 1(NULL)
TINYINT不允許NULL = 1
SMALLINT允許為NULL = 2+1(NULL)
SMALLINT不允許為NULL = 2
INT允許為NULL = 4+1(NULL)
INT不允許為NULL = 4
日期時間型的key_len計算:(針對mysql5.5及之前版本)
DATETIME允許為NULL = 8 + 1(NULL)
DATETIME不允許為NULL = 8
TIMESTAMP允許為NULL = 4 + 1(NULL)
TIMESTAMP不允許為NULL = 4
3.索引使用有效方式
假設:聯合索引類型(a,b,c)
正常使用語法方式:a>b>c, a>c>b, c>b>a, b>c>a, c>a>b, b>a>c均是有效的
例如:
EXPLAIN select * from user where pid = 100010 and name like '2000%' and user_no ='300010'
EXPLAIN select * from user where pid = 100010 and user_no ='300010' and name like '2000%'
EXPLAIN select * from user where name like '2000%' and user_no ='300010' and pid = 100010
EXPLAIN select * from user where user_no ='300010' and name like '2000%' and pid = 100010
EXPLAIN select * from user where name like '2000%' and pid = 100010 and user_no ='300010'
EXPLAIN select * from user where user_no ='300010' and pid = 100010 and name like '2000%'
這幾個查詢的結果,key_len長度均為133:
總結:索引最左邊的參數存在的話,符合索引規則的語句就能使用索引
1.位置失效情況:
a>c: EXPLAIN select * from user where pid = 100010 and user_no ='300010'
結果如下:
總結:只有a用到索引
c>a: EXPLAIN select * from user where user_no ='300010' and pid = 100010
結果如下:
總結:只有a用到索引
a>b 或者 b>a: 均用到索引,例子省略
2.模糊查詢失效:
%xxx 情況:EXPLAIN select * from user where name like '%2000' and pid = 100010
結果如下:
總結: 模糊索引失效,只有索引a有效
xxx% 情況:EXPLAIN select * from user where name like '2000%' and pid = 100010
結果如下:
總結:索引有效
3.條件查詢失效:
1.查詢數據量達到總數據量的30%左右就不會使用索引
2.如果有limit限制條數,則查詢數據量達到總數據量的99.2%左右不會使用索引
4.<>或者!=失效:
EXPLAIN select * from user where name like '2000%' and pid != 100010
結果如下:
總結:索引失效
5.is null和 is not null :
EXPLAIN select * from user where name is not null and pid = 100010
結果如下:
總結:b索引失效,只有a成功
未完待續!!!