mysql中包含長字段索引的優化

不一樣於oracle,在mysql的Innodb存儲引擎中,對索引的總長度有限制。在mysql 5.7中(https://dev.mysql.com/doc/refman/5.7/en/innodb-restrictions.html),默認爲3072。html

If innodb_large_prefix is enabled (the default), the index key prefix limit is 3072 bytes for InnoDB tables that use DYNAMIC orCOMPRESSED row format. If innodb_large_prefix is disabled, the index key prefix limit is 767 bytes for tables of any row format.mysql

innodb_large_prefix is deprecated and will be removed in a future release. innodb_large_prefix was introduced in MySQL 5.5 to disable large index key prefixes for compatibility with earlier versions of InnoDB that do not support large index key prefixes.sql

The index key prefix length limit is 767 bytes for InnoDB tables that use the REDUNDANT or COMPACT row format. For example, you might hit this limit with a column prefix index of more than 255 characters on a TEXT or VARCHAR column, assuming a utf8mb3character set and the maximum of 3 bytes for each character.mongodb

Attempting to use an index key prefix length that exceeds the limit returns an error. To avoid such errors in replication configurations, avoid enabling innodb_large_prefix on the master if it cannot also be enabled on slaves.json

The limits that apply to index key prefixes also apply to full-column index keys.oracle

因此在GBK編碼中,最大能夠到1536個字符,utf8/utf8mb3,1024個字符,utf8mb4爲768個字符。這一限制爲自然限制(mariadb由於採用Innodb引擎,該限制一樣存在),沒法繞開。app

drop table big_index_test;
create table big_index_test(id int,content varchar(1000)) ROW_FORMAT=DYNAMIC CHARACTER set = utf8mb4 ;
create index idx_big_index on big_index_test(content);性能

[SQL]create index idx_big_index on big_index_test(content);
[Err] 1071 - Specified key was too long; max key length is 3072 bytes優化

相對於oracle來講,若是定義存在這種狀況,即便記錄沒有或不多,仍然沒法利用索引覆蓋查詢實現一些寬表的優化。this

所以,對於mysql而言,對於一些定義很長的detail,最好的方式是垂直拆表,也就是將id和detail字段存儲在單獨的表中,而後業務代碼中二次select的方式優化。若是detail字段是json類型的話,能夠直接存儲爲json類型或存儲在NoSQL中如mongodb。

注:當年5.6的時候,幫一個產品優化過mysql,mysql在大字段的處理上性能很是低下。

相關文章
相關標籤/搜索