我遇到了 MySQL 的奇怪行为。查询执行(即explain [QUERY] 所示的索引的使用)和执行所需的时间取决于where 子句的元素。
这是出现问题的查询:
select distinct
e1.idx, el1.idx, r1.fk_cat, r2.fk_cat
from ent e1, ent_leng el1, rel_c r1, _tax_c t1, rel_c r2, _tax_c t2
where el1.fk_ent=e1.idx
and r1.fk_ent=e1.idx and ((r1.fk_cat=43) or (r1.fk_cat=t1.fk_cat1 and t1.fk_cat2=43))
and r2.fk_ent=e1.idx and ((r2.fk_cat=10) or (r2.fk_cat=t2.fk_cat1 and t2.fk_cat2=10))
对应的解释输出为:
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra
+----+-------------+-------+--------+-------------------------+---------+---------+---------------+-------+------------------------------------
| 1 | SIMPLE | el1 | index | fk_ent | fk_ent | 4 | NULL | 15002 | Using index; Using temporary
| 1 | SIMPLE | e1 | eq_ref | PRIMARY | PRIMARY | 4 | DB.el1.fk_ent | 1 | Using index
| 1 | SIMPLE | r1 | ref | fk_ent,fk_cat,fks | fks | 4 | DB.e1.idx | 1 | Using where; Using index
| 1 | SIMPLE | r2 | ref | fk_ent,fk_cat,fks | fks | 4 | DB.el1.fk_ent | 1 | Using index
| 1 | SIMPLE | t1 | index | fk_cat1,fk_cat2,fk_cats | fk_cats | 8 | NULL | 69 | Using where; Using index; Distinct;
| | | | | | | | | | Using join buffer
| 1 | SIMPLE | t2 | index | fk_cat1,fk_cat2,fk_cats | fk_cats | 8 | NULL | 69 | Using where; Using index; Distinct;
| Using join buffer
如您所见,单列索引与其所属的列具有相同的名称。我还添加了一些无用的索引以及使用的索引,只是为了查看它们是否会更改执行(它们不会)。
执行大约需要 4.5 秒。
当我将列 entl1.name 添加到选择部分(没有其他更改)时,el1 中的索引 fk_ent 不能再使用:
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra
+----+-------------+-------+--------+-------------------------+---------+---------+---------------+-------+------------------------------------
| 1 | SIMPLE | el1 | ALL | fk_ent | NULL | NULL | NULL | 15002 | Using temporary
现在执行大约需要 8.5 秒。
我一直认为查询的选择部分不会影响引擎对索引的使用,也不会以这种方式影响性能。
省略属性不是解决方案,我必须选择更多属性。更糟糕的是,使用形式的查询更加复杂,这使得性能问题成为一个大问题。
所以我的问题是:1)这种奇怪行为的原因是什么?2)如何解决性能问题?
谢谢你的帮助!格雷德