简体   繁体   English

性能改进:左外部Join,Order By,子查询:主查询未选择索引

[英]performance improvement: Left outer Join, Order By, Subquery: Index not picked up by the main query

table 1: 表格1:

pk1 pk2 pk3 field1 field2 modifieddate version pk1 pk2 pk3字段1字段2修改日期版本

table 2: 表2:

pk1 pk3 tab1 tab2 tab3 pk1 pk3 tab1 tab2 tab3

(pk1,pk2)-primary key for table1 (pk1,pk3)-primary key for table2 (pk1,pk2)-表1的主键(pk1,pk3)-表2的主键

pk1,pk3 -foreign key pk1,pk3-外键

The sample query is like this: 示例查询如下所示:

select *.tab1, tab2.field1
from table1 tab1
LEFT JOIN table2 tab2
ON (tab1.pk1 =tab2.pk1 AND tab1.pk3 = tab2.pk3)
WHERE (tab1.pk1= 'xx' OR tab1.pk1 = 'yy')
AND (tab1.pk3 = 'aa' OR tab1.pk3 is null)
AND (tab1.modifieddate >'somevalue' OR (tab1.modifieddate = 'somevalue' AND tab1.pk2 >    ' \n') )
AND tab1.field1 = (select max(field1) from table1
where ((tab1.pk1= 'xx' OR tab1.pk1 = 'yy') 
AND (tab1.pk3 = 'aa' OR tab1.pk3 is null) AND field3 = tab1.field3))
ORDER BY modifieddate desc,pk1 desc
limit 0,50

The indexes created are: 创建的索引是:

index1(pk1,pk3,modifieddate,pk2,field3) index1(pk1,pk3,modifieddate,pk2,field3)

index2(pk1,modifieddate,pk2,field3) index2(pk1,modifieddate,pk2,field3)

foreignkeyindex(pk1,pk3) 外键索引(pk1,pk3)

subqueryindex(pk1,pk3,field2) 子查询索引(pk1,pk3,field2)

As I analyzed, I found that using OR in the outer query is the reason for not taking up index. 根据我的分析,我发现在外部查询中使用OR是不占用索引的原因。 http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html-- > last comment by Stephen Dewey. http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html-- > Stephen Dewey的最新评论。

I gone through many posts of stackoverflow and tried using UNION ALL. 我遍历了许多stackoverflow的帖子,并尝试使用UNION ALL。 In that case, for my scenario, I ended up with a derived table. 在这种情况下,对于我的情况,我最终得到了一个派生表。 Can a derived table be made to use the indexes? 可以使派生表使用索引吗?


EDIT Explain plan: 编辑说明计划:

id select-type          table   type        possible_keys             key       key-len   ref          rows     extra
1   primary             tab1    range       primary,index1,index2      pk3       497      null           734     using where;using filesort
2   primary             tab2    ref         primary,forignkeyindex,pk3 pk3       110   db.tab1.pk3         1       
3   dependent subquery  table1  ref_or_null pk3,subqueryindex     subqueryindex  497  tab1.pk3,tab1.field1 2     using where

Would you please give some help on optimizing this query? 您能否在优化此查询方面提供一些帮助? :) :)

You join using 您加入使用

tab1.pk1 =tab2.pk1 AND tab1.pk3 = tab2.pk3)

try creating an index with the keys you use to join, ie 尝试使用用于连接的键创建索引,即

table1: index1(pk1,pk3)
table2: index2(pk1,pk3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM