문제

If I have a unique index on a table that covers 2 fields, should I add another index on each field?

Example:

My table looks like this:

CREATE TABLE IF NOT EXISTS `my_table` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `usersID` int(11) NOT NULL,
  `userTypesID` int(11) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

I then add a unique index which covers both usersID and userTypesID:

ALTER TABLE  `my_table` ADD UNIQUE  `usersID_userTypesID` (  `usersID` ,  `userTypesID` )

Is it worth me adding 2 more indexes, one on usersID and another on userTypesID? e.g:

ALTER TABLE  `my_table` ADD INDEX (  `usersID` )
ALTER TABLE  `my_table` ADD INDEX (  `userTypesID` )

Would adding these extra indexes speed up some queries? Such as:

SELECT      `usersID`
FROM        `my_table`
WHERE       `userTypesID` = 101

Or

SELECT      `usersTypesID`
FROM        `my_table`
WHERE       `usersID` = 29
도움이 되었습니까?

해결책

In theory the index on (usersID, userTypesID) will also act as an index on usersID by itself, because it's the left most column.

You would benefit from an index on userTypesID too.

다른 팁

You don't need additional indexes, see here. Also try SHOW INDEXES FROM my_table

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top