我们在 MySQL 中有下表。
CREATE TABLE `user_team` (
`user_id` int(11) NOT NULL,
`team_id` int(10) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`user_id`,`team_id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
此处是否需要 KEY user_id (user_id)
?我记得在某处读到说复合索引的第一列自动有一个索引。好像找不到来源。
最佳答案
来自 MySQL documentation :
If the table has a multiple-column index, any leftmost prefix of the index can be used by the optimizer to look up rows. For example, if you have a three-column index on (col1, col2, col3), you have indexed search capabilities on (col1), (col1, col2), and (col1, col2, col3).
使用您的 (user_id, team_id)
示例索引,仅在 user_id
上过滤的查询可以使用此索引,因为 B 树首先在该字段上建立索引。它随后也按 team_id
拆分并不重要,因为您只是在查找匹配或不匹配某个 user_id
值或多个值的所有记录。
现在,如果您还想支持仅在 team_id
上过滤的查询,那么您至少需要添加一个其他索引。在这种情况下,您当前的复合索引不会涵盖此类查询。
关于mysql - 复合索引的第一列是否需要另一个索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67013964/