mysql 小值集的多个索引
mysql multiple indexes for small sets of values
我有一个 table 用于记录数据,例如
TABLE IF NOT EXISTS `message_log` (
`id` int(8) NOT NULL AUTO_INCREMENT,
`user_id` int(8) unsigned NOT NULL,
`channel` tinyint(8) unsigned NOT NULL DEFAULT '0',
`type` tinyint(4) NOT NULL DEFAULT '0',
`message` varchar(255) NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`confirmed` datetime DEFAULT NULL,
PRIMARY KEY (`id`,`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
/*!50100 PARTITION BY HASH (user_id)
PARTITIONS 11 */ AUTO_INCREMENT=4569
(注意 - 我知道它应该是 InnoDB,但这不是问题)
关于搜索,可以在user_id、user_id和频道上搜索,也可以在user_id和频道和类型上搜索。
user_id 可以是任意数字。
通道为 1-20。
类型为 1-3。
现在 user_id 似乎是一个明显的索引候选者,但我是否需要索引频道和类型,因为它们的可能性相对较小?
在这种特殊情况下,当您有基于 user_id
channel
和 type
的搜索时,您可以使用覆盖索引(复合),这将是有效的。
If the table has a multiple-column index, any leftmost prefix of the
index can be used by the optimizer to look up rows.
http://dev.mysql.com/doc/refman/5.0/en/multiple-column-indexes.html
因此您可以将索引添加为
alter table message_log add index search_idx(user_id,channel,type)
我有一个 table 用于记录数据,例如
TABLE IF NOT EXISTS `message_log` (
`id` int(8) NOT NULL AUTO_INCREMENT,
`user_id` int(8) unsigned NOT NULL,
`channel` tinyint(8) unsigned NOT NULL DEFAULT '0',
`type` tinyint(4) NOT NULL DEFAULT '0',
`message` varchar(255) NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`confirmed` datetime DEFAULT NULL,
PRIMARY KEY (`id`,`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
/*!50100 PARTITION BY HASH (user_id)
PARTITIONS 11 */ AUTO_INCREMENT=4569
(注意 - 我知道它应该是 InnoDB,但这不是问题)
关于搜索,可以在user_id、user_id和频道上搜索,也可以在user_id和频道和类型上搜索。 user_id 可以是任意数字。 通道为 1-20。 类型为 1-3。
现在 user_id 似乎是一个明显的索引候选者,但我是否需要索引频道和类型,因为它们的可能性相对较小?
在这种特殊情况下,当您有基于 user_id
channel
和 type
的搜索时,您可以使用覆盖索引(复合),这将是有效的。
If the table has a multiple-column index, any leftmost prefix of the index can be used by the optimizer to look up rows.
http://dev.mysql.com/doc/refman/5.0/en/multiple-column-indexes.html
因此您可以将索引添加为
alter table message_log add index search_idx(user_id,channel,type)