有人可以告诉我为什么mysql在以下查询中未使用正确的索引吗SELECT `Slugs`.`slug` FROM `slugs` AS `Slugs`WHERE `Slugs`.`country_id` = 1 AND `Slugs`.`expired` = 0LIMIT 308400,300我为where子句中引用的两列创建了一个cmposite索引表slugs的表结构CREATE TABLE IF NOT EXISTS `slugs` ( `id` int(11) NOT NULL AUTO_INCREMENT, `slug` varchar(255) NOT NULL, `post_fields` text NOT NULL, `slugdata` text NOT NULL, `updated_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `country_id` int(11) NOT NULL DEFAULT '1', `expired` int(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `slug_2` (`slug`,`country_id`), KEY `updated_date` (`updated_date`), KEY `country_id` (`country_id`), KEY `slug` (`slug`), KEY `expired` (`expired`), KEY `country_id_2` (`country_id`,`expired`)) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1612485 ;索引:Keyname Type Unique Packed Field Cardinality Collation Null CommentPRIMARY BTREE Yes No id 1406994 Aslug_2 BTREE Yes No slug 1406994 A country_id 1406994 Aupdated_date BTREE No No updated_date 21 Acountry_id BTREE No No country_id 21 Aslug BTREE No No slug 1406994 Aexpired BTREE No No expired 21 Acountry_id_2 BTREE No No country_id 21 A expired 21 A解释输出id select_type table type possible_keys key key_len ref rows Extra1 SIMPLE Slugs ref country_id,expired,country_id_2 country_id 4 const 670284 Using where 最佳答案 您是什么意思,它没有使用正确的索引?country_id和country_id_2的基数都非常低,并且实际上两个索引都相同-因此,使用基于2列的索引没有任何好处。这意味着很少有过期 0的记录。但是,为什么过期索引的基数也为21?什么是输出:SELECT 'expired' AS fld, COUNT(*) AS distinct_values, AVG(n) AS rowsFROM(SELECT expired AS v , COUNT(*) AS n FROM slugs GROUP BY expired) ilv1UNIONSELECT 'country_id',, COUNT(*) AS distinct_values, AVG(n) AS rowsFROM(SELECT country_id AS v , COUNT(*) AS n FROM slugs GROUP BY country_id) ilv2 SELECT 'expired:country_id',, COUNT(*) AS distinct_values, AVG(n) AS rowsFROM(SELECT CONCAT(expired, country_id) AS v , COUNT(*) AS n FROM slugs GROUP BY CONCAT(expired, country_id)) ilv3;关于mysql - MySQL索引问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9062642/
10-11 02:49