mysql - 复合索引的第一列是否需要另一个索引?

标签 mysql sql indexing

我们在 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/

相关文章:

mysql - 多列上的多个索引

python - 如何组合两列以创建第三列,通过方法从组中获取属性?

MySQL 捆绑安装

MySql 查询选择然后删除

python - 为什么这个循环不每五秒显示一次更新的对象计数?

sql - Presto 生成 JSON 结果

sql - 如何检查Oracle sql中列之间的单词的前两个字符是否相等

mysql - 在查询中重命名值

java - com.microsoft.sqlserver.jdbc.SQLServerException : MSI Token failure: Failed to acquire token from MSI Endpoint

sql - 为什么表中的记录排序不是按照聚集索引?