As long as the user-defined index field contains the field in the primary key, this field will not be automatically added to the index by InnoDB. However, if the index field does not contain a full package
As long as the user-defined index field contains the field in the primary key, this field will not be automatically added to the index by InnoDB. However, if the index field does not contain a full package
(I) principle:
As long as the index field defined by the user contains the field in the primary key, this field will not be automatically added to the index by InnoDB.
However, if the index field does not fully contain the primary key field, InnoDB adds the remaining primary key fields to the end of the index.
(Ii) Example
Example 1:
Create table t (
A char (32) not null primary key,
B char (32) not null,
KEY idx1 (a, B ),
KEY idx2 (B,)
) Engine = InnoDB;
Idx1 and idx2 indexes have the same internal size and no difference.
Example 2:
Create table t (
A char (32) not null,
B char (32) not null,
C char (32) not null,
D char (32) not null,
Primary key (a, B)
KEY idx1 (c, ),
KEY idx2 (d, B)
) Engine = InnoDB;
In this table, InnoDB will automatically complete the primary key dictionary. idx1 actually stores (c, a, B) internally, and idx2 actually stores (d, B, a) internally)
However, the automatically added field and Server layer are unknown, so the MySQL optimizer does not know the existence of this field. If you have a query:
SELECT * FROM t WHERE d = x1 AND B = x2 ORDER BY;
In fact, the idx2 (d, B, a) in the internal storage can make this query completely indexed, but the Server layer does not know,
Therefore, the MySQL Optimizer may select idx2 (d, B) to filter and sort field a, or directly use PK scan to avoid sorting.
If we define the table structure as KEY idx2 (d, B, a), MySQL will know that all the three fields (d, B, a) are indexed,
In addition, InnoDB found that the user-defined index contains all primary key fields, and no more storage space is added.
(Iii) Suggestions
Therefore, we sincerely recommend that you add the primary key field and,
There is no loss, but it may surprise you.
,