1

我对 where 子句中的列进行查询,这些列是主键的一部分,并且在所有列上都有外键索引。

EXPLAIN SELECT   aggEI.c_id AS companyId, aggEI.ei_uid AS uuid
FROM AGG_EI AS aggEI 
WHERE  aggEI.c_id in (8) and aggEI.tg_id IN (1,2,3,4,5,6,7)
       AND aggEI.dt_id = 20130506

我还在 ( c_id, tg_id, dt_id) 上定义了多个列索引,但 EXPLAIN 显示它正在使用外键索引c_id

 1 SIMPLE   aggEI   ref PRIMARY,datedm_id_UNIQUE,agg_ei_comdm_fk_idx,agg_ei_datedm_fk_idx,agg_ei_topgrp_fk_idx,comp_uuid    agg_ei_comdm_fk_idx 8   const   65986   Using where; Using index

agg_ei_comdm_fk_idx 是外键索引,comp_uuid 是 ( , , )c_id上的多列索引c_idtg_iddt_id

有人可以解释为什么会这样吗

编辑:创建表

          'CREATE TABLE `AGG_EI` (
              `dt_id` int(11) NOT NULL,
              `c_id` bigint(20) NOT NULL,
              `tg_id` bigint(20) NOT NULL,
              `ei_uid` varchar(150) NOT NULL
              `ei_name` varchar(150) NOT NULL,
               `rating` double NOT NULL,
              `cnt` double NOT NULL
               PRIMARY KEY (`dt_id`,`c_id`,`tg_id`,`ei_uid`),
                UNIQUE KEY `datedm_id_UNIQUE` (`dt_id`,`c_id`,`ei_uid`,`tg_id`),
               KEY `agg_ei_comdm_fk_idx` (`c_id`),
               KEY `agg_ei_datedm_fk_idx` (`dt_id`),
               KEY `agg_ei_topgrp_fk_idx` (`tg_id`),
               KEY `comp_uuid` (`c_id`,`tg_id`,`dt_id`),
               CONSTRAINT `agg_ei_comdm_fk` FOREIGN KEY (`c_id`) REFERENCES `COMPDM`     (`c_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
                CONSTRAINT `agg_ei_datedm_fk` FOREIGN KEY (`dt_id`) REFERENCES `DATEDM` (`dt_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
                CONSTRAINT `agg_ei_topgrp_fk` FOREIGN KEY (`tg_id`) REFERENCES `TOPGRP` (`tg_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
             ) ENGINE=InnoDB DEFAULT CHARSET=utf8'
4

2 回答 2

4

MySQL 正在使用它认为性能最好的计划执行查询。很可能,它确定限制c_id为单个值会将结果集减少到足够少的行,从而麻烦地处理另一个索引中的额外列是不值得的。MySQL 的最佳猜测是,使用 just 限制行c_id然后只过滤内存中的那些行会更快。仅仅因为你有一个索引并不意味着这是最快的计划。

于 2013-05-23T08:08:50.770 回答
-1

您可以强制 mysql 使用如下索引:

EXPLAIN 
SELECT   
    aggEI.c_id AS companyId, 
    aggEI.ei_uid AS uuid
FROM 
    AGG_EI AS aggEI FORCE INDEX(`comp_uuid`)
WHERE  
    aggEI.c_id in (8) 
    AND aggEI.tg_id IN (1,2,3,4,5,6,7)
    AND aggEI.dt_id = 20130506
于 2013-05-23T08:36:25.697 回答