简体   繁体   中英

How can I make my mysql query with many left joins execute quicker?

I have written a query and locally it's working fine. When it's live I am getting this error:

ERROR 1104: The SELECT would examine too many records and probably take a very long time. Check your WHERE and use SET OPTION SQL_BIG_SELECTS=1 if the SELECT is ok

I have added SET SQL_BIG_SELECTS=1; . It's working now, but it is running very slowly. Can any one sort out my query, ege instead of LEFT JOIN use another method. This is my query:

    SELECT sh.*,
       ps.provider_name,
       ps.photo_path AS photo
FROM   scholarship sh
       left join cat_category_sch ccs
              ON ccs.scholar_id = sh.id
       left join elg_countries_sch elg
              ON elg.scholar_id = sh.id
       left join study_level_sch sls
              ON sls.scholar_id = sh.id
       left join taken_country_sch tcs
              ON tcs.scholar_id = sh.id
       left join providers ps
              ON ps.id = sh.provider
       left join countires c1
              ON c1.id = elg.county_id
       left join countires c2
              ON c1.id = tcs.county_id
       left join study_level sl
              ON sl.id = sls.study_level_id
WHERE  sh.status = 1
       AND sh.ain_status = 1
       AND sh.deadline >= Date_sub(Now(), interval 1 year)
GROUP  BY sh.id
ORDER  BY sh.id DESC  

Thanks in advance

LEFT implies that the 'right' table may not have a 'matching' row. Yet you don't check for existence or absence with IS NULL or IS NOT NULL. So, I suspect LEFT is unnecessary? (I bring the up because (1) it may distract from the real problem and (2) it may slow down the query.)

If LEFT is required, then ON tcs.scholar_id = sh.id needs an index on scholar_id . (Etc.)

Also the compound index INDEX(status, ain_status, deadline) is likely to help.

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