我对该表的最佳索引选项有点困惑。我想要对 ServiceID 和 TagID 进行搜索和加入。我还需要确保两者的组合是唯一的。
CREATE TABLE IF NOT EXISTS `service-tag` (
`ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`ServiceID` int(10) unsigned NOT NULL,
`TagID` int(10) unsigned NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `ServiceID` (`ServiceID`,`TagID`),
KEY `TagID` (`TagID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=39 ;
是否有必要在 TagID 上添加第二个索引,或者它是否会因为成为 UNIQUE 索引中的第二列而自动正确建立索引?
最佳答案
如果您有一个多列索引(如 ServiceID
索引),那么当您仅搜索 TagID
时,MySQL 无法使用该索引。用通俗的语言来说,当您只需要 TagID
时,MySQL 无法在不使用 ServiceID
的情况下“到达”索引。
因此,如果您确实计划仅在语句中使用 TagID
,那么您会希望保留该索引。
如果您从未计划只查询 TagID
并且您的所有查询将始终使用 ServiceID
和 TagID
,那么是的,不需要 TagID
仅索引。
此行为记录在手册中:
https://dev.mysql.com/doc/refman/5.0/en/multiple-column-indexes.html
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).
MySQL cannot use the index to perform lookups if the columns do not form a leftmost prefix of the index.
关于mysql - 这些 MySQL 索引是否重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32869818/