简体   繁体   中英

how do I make this query run faster?

I have this SQL query running on a PHP website. This is an old site and the query was build by previous developer few years ago. But now as the site data is increased to around 230mb, this query has become pretty slow to execute. Take around 15-20 seconds. Is there any way I can make this run faster?

SELECT DISTINCT
    NULL AS bannerID,
    C1.url AS url,
    LOWER(C1.Organization) AS company_name,
    CONCAT(
        'https://mywebsite.co.uk/logos/',
        C1.userlogo
    ) AS logo_url
FROM
    Company AS C1
INNER JOIN Vacancy AS V1 ON LOWER(V1.company_name) = LOWER(C1.Organization)
WHERE
    V1.LiveDate <= CURDATE() 
AND url = '' 
AND V1.ClosingDate >= CURDATE()
AND C1.flag_show_logo = 1

As commented, your query is suffering from being non-sargable due to the use of lower function.

Additionally I suspect you can remove the distinct by using exists instead of joining your tables

select null as bannerID,
    C1.url as url,
    Lower(C1.Organization) as company_name,
    Concat('https://mywebsite.co.uk/logos/', C1.userlogo) as logo_url
from Company c
where c.flag_show_logo = 1
  and c.url = '' 
and exists (
    select * from Vacancy v 
    where v.LiveDate <= CURDATE() 
    and v.ClosingDate >= CURDATE()
    and v.company_name = c.Organization
)

Avoid the sargable problem by changing to

ON  V1.company_name = C1.Organization

and declaring those two columns to be the same collation, namely a collation ending with "_ci".

And have these composite indexes:

C1:  INDEX(flag_show_logo, url, Organization,  userlogo)
V1:  INDEX(company_name, LiveDate, ClosingDate)

(These indexes should help Stu's answer, too.)

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