MySQL索引的索引長度問題

MySQL的每個單表中所創建的索引長度是有限制的,且對不同存儲引擎下的表有不同的限制。
在MyISAM表中,創建組合索引時,創建的索引長度不能超過1000,注意這裏索引的長度的計算是根據表字段設定的長度來標量的,例如:
create table test(id int,name1 varchar(300),name2 varchar(300),name3 varchar(500))charset=latin1 engine=myisam;
create index test_name on test(name1,name2,name3);
此時報錯:Specified key was too long;max key length is 1000 bytes.

修改表結構:alter table test convert to charset utf8;
create index test_name3 on test(name3).
此時warning:Specified key was too long;max key length is 1000 bytes.但是索引創建成功,查看錶結構可以看到創建的索引是一個前綴索引:‘key test_name3(name3(333))’

得出的結論是:對於myisam表,如果創建組合索引,所創建的索引長度和不能超過1000 bytes,否則會報錯,創建失敗;對於myisam的單列索引,最大長度也不能超過1000,否則會報警,但是創建成功,最終創建的是前綴索引(取前333個字節)。

在Innodb表中,創建組合索引:
create table test1(id int,name1 varchar(300),name2 varchar(300),name3 varchar(500))charset=latin1 engine=innodb;
create index test1_name on test(name1,name2,name3);
此時給出warning:Specified key was too long;max key length is 767 bytes.

修改表結構:alter table test1 convert to charset utf8;
create index test1_name3 on test(name3).
此時給出warning:Specified key was too long;max key length is 767 bytes.

得出的結論是:對於創建innodb的組合索引,如果各個列中的長度不超過767,則不再計算所有列的總長度,如果有超過767的,則給出報警,索引最後創建成功,但是對於超過767字節的列取前綴索引;對於innodb的單列索引,超過767的,給出warning,最終索引創建成功,取前綴索引(取前255字節)。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章