简体   繁体   中英

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

table 1:

pk1 pk2 pk3 field1 field2 modifieddate version

table 2:

pk1 pk3 tab1 tab2 tab3

(pk1,pk2)-primary key for table1 (pk1,pk3)-primary key for table2

pk1,pk3 -foreign key

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)

index2(pk1,modifieddate,pk2,field3)

foreignkeyindex(pk1,pk3)

subqueryindex(pk1,pk3,field2)

As I analyzed, I found that using OR in the outer query is the reason for not taking up index. http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html-- > last comment by Stephen Dewey.

I gone through many posts of stackoverflow and tried using 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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