1

我在 MySQL 中遇到了枚举字段的问题。当我只使用一个值 SELECT * FROM test WHERE t IN ('new') 时,一切都很好,但是如果有多个值 SELECT * FROM test WHERE t IN ('new','deleted') MySQL 没有完全使用索引,因此此查询的性能非常低。有可能用它做点什么吗?

CREATE TABLE `test` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`t` ENUM('new','active','deleted') NOT NULL,
PRIMARY KEY (`id`),
INDEX `t` (`t`)
)
ENGINE=MyISAM;


INSERT INTO test SET t = 'new';
INSERT INTO test SET t = 'new';
INSERT INTO test SET t = 'active';
INSERT INTO test SET t = 'active';
INSERT INTO test SET t = 'deleted';
INSERT INTO test SET t = 'deleted';


EXPLAIN SELECT * FROM test WHERE t IN ('new');
id|select_type|table|type|possible_keys|key|key_len|ref  |rows|Extra
1 |SIMPLE     |test |ref |t            |t  |1      |const|2   |Using index condition

EXPLAIN SELECT * FROM test WHERE t IN ('new','deleted');
id|select_type|table|type|possible_keys|key |key_len|ref |rows|Extra
1 |SIMPLE     |test |ALL |t            |NULL|NULL   |NULL|6    |Using where
4

1 回答 1

1

MySQL 在第二种情况下没有使用索引这一事实并不意味着性能会很差(尽管可能会如此)。索引的差异不是很大,因此查询优化器认为不是扫描索引两次(每个值一次)然后读取每个选定索引的行,扫描表和直接挑出行。

像这样的索引如果要有用,通常需要大量的 TLC (Tender Loving Care)。看看这里了解更多。

于 2013-01-23T11:50:43.510 回答