MySQL 5.7.12 开始
测试结果
create table booboo_db1.t20211018 (id int primary key, a varchar(5000)); |
官方说明
Column Prefix Key Parts
For string columns, indexes can be created that use only the leading part of column values, using *col_name*(*length*) syntax to specify an index prefix length:
Prefixes can be specified for
CHAR,VARCHAR,BINARY, andVARBINARYkey parts.Prefixes must be specified for
BLOBandTEXTkey parts. Additionally,BLOBandTEXTcolumns can be indexed only forInnoDB,MyISAM, andBLACKHOLEtables.Prefix limits are measured in bytes. However, prefix lengths for index specifications in
CREATE TABLE,ALTER TABLE, andCREATE INDEXstatements are interpreted as number of characters for nonbinary string types (CHAR,VARCHAR,TEXT) and number of bytes for binary string types (BINARY,VARBINARY,BLOB). Take this into account when specifying a prefix length for a nonbinary string column that uses a multibyte character set.Prefix support and lengths of prefixes (where supported) are storage engine dependent. For example, a prefix can be up to 767 bytes long for
InnoDBtables or 3072 bytes if theinnodb_large_prefixoption is enabled. ForMyISAMtables, the prefix length limit is 1000 bytes. TheNDBstorage engine does not support prefixes (see Section 21.2.7.6, “Unsupported or Missing Features in NDB Cluster”).
As of MySQL 5.7.17, if a specified index prefix exceeds the maximum column data type size, CREATE INDEX handles the index as follows:
- For a nonunique index, either an error occurs (if strict SQL mode is enabled), or the index length is reduced to lie within the maximum column data type size and a warning is produced (if strict SQL mode is not enabled).
- For a unique index, an error occurs regardless of SQL mode because reducing the index length might enable insertion of nonunique entries that do not meet the specified uniqueness requirement.
The statement shown here creates an index using the first 10 characters of the name column (assuming that name has a nonbinary string type):
CREATE INDEX part_of_name ON customer (name(10)); |
If names in the column usually differ in the first 10 characters, lookups performed using this index should not be much slower than using an index created from the entire name column. Also, using column prefixes for indexes can make the index file much smaller, which could save a lot of disk space and might also speed up INSERT operations.