mysql - Slow query with lot of joins and 'IN' statement -
i have slow query , believe due 'in' statement. list of ids in 'in' statement can large, 250+. query run 2+ seconds every time, , slow.
is there way speed up?
select u.achternaam achternaam, u.code code, srt.niveaus niveaus, srt.soortid soortid,ifnull( scr.gehaald,'0')as gehaald, ifnull( scr.gespeeld,'0')as gespeeld, if( srt.niveaus =1,'n.v.t.', ifnull(scr.huidigniveau,'0') )as niveautext gebruikers u left join ( select scoreid,schoolcode, soortid, userid, gehaald, gespeeld, huidigniveau scores) scr on scr.userid = u.code left join ( select soortid,niveaus,spelid,titel,verberg soorten soortid in (13,14,15,16,17,561,566,567,568,574,575,1,100,101,102,103,104,105,107,108,109,11,110,112,113,114,115,116,117,118,12,120,121,122,123,124,125,126,127,128,129,130,131,133,134,137,138,140,141,144,145)) srt on scr.soortid = srt.soortid left join(select spelnaam,spelid,vakid spellen) g on srt.spelid=g.spelid left join(select vakid,vaknaam vakken) vak on g.vakid=vak.vakid u.groepsid='28' , u.schoolcode ='1' , srt.verberg =0 order achternaam,vak.vaknaam,g.spelnaam,srt.titel asc
result of explain select:
don't use subqueries, join tables directly.
note srt.verberg = 0
test should in on
clause, not where
clause. when use left join
, conditions on second table should in on
, unless you're testing null
results not finding match.
select u.achternaam achternaam, u.code code, srt.niveaus niveaus, srt.soortid soortid,ifnull( scr.gehaald,'0')as gehaald, ifnull( scr.gespeeld,'0')as gespeeld, if( srt.niveaus =1,'n.v.t.', ifnull(scr.huidigniveau,'0') )as niveautext gebruikers u left join scores scr on scr.userid = u.code left join soorten srt on scr.soortid = srt.soortid , srt.soortid in (13,14,15,16,17,561,566,567,568,574,575,1,100,101,102,103,104,105,107,108,109,11,110,112,113,114,115,116,117,118,12,120,121,122,123,124,125,126,127,128,129,130,131,133,134,137,138,140,141,144,145) , srt.verberg = 0 left join spellen g on srt.spelid=g.spelid left join vakken vak on g.vakid=vak.vakid u.groepsid='28' , u.schoolcode ='1' order achternaam, vak.vaknaam, g.spelnaam, srt.titel asc
also, make sure need use left join
rather inner join
. left join
should used when want result include rows first table have no matches in second table. inner join
performance better, should use whenever appropriate.
Comments
Post a Comment