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
, andVARBINARY
key parts.Prefixes must be specified for
BLOB
andTEXT
key parts. Additionally,BLOB
andTEXT
columns can be indexed only forInnoDB
,MyISAM
, andBLACKHOLE
tables.Prefix limits are measured in bytes. However, prefix lengths for index specifications in
CREATE TABLE
,ALTER TABLE
, andCREATE INDEX
statements 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
InnoDB
tables or 3072 bytes if theinnodb_large_prefix
option is enabled. ForMyISAM
tables, the prefix length limit is 1000 bytes. TheNDB
storage 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.