简体   繁体   中英

MySQL order_by optimization

we have a complex query that uses joins across tables and order_by.

Sample below:

select distinct `accounts`.`id`,
    `accounts`.`number_of_listings` as alias_0
from `accounts`
left outer join `revenue_item_account_leads` on `revenue_item_account_leads`.`account_id` = `accounts`.`id`
left outer join `matches` on `matches`.`matchable_id` = `accounts`.`id`
    and `matches`.`matchable_type` = 'Account'
where `accounts`.`locale_id` = 1
    and (
        revenue_item_account_leads.platform_id is null
        or (revenue_item_account_leads.platform_id != 6)
        )
    and (
        matches.matched_matchable_id is null
        or (
            matches.matched_matchable_id in (14, 31, 37)
            and matches.score < 0.75
            )
        or (matches.matched_matchable_id not in (14, 31, 37))
        )
    and (accounts.number_of_listings > 0)
order by `accounts`.`number_of_listings` desc LIMIT 25 OFFSET 0

The query WITHOUT the order_by finishes in 1 second. The query WITH the order_by finishes in 5 seconds (rendering it un-useable for us in production).

There's already an index on accounts.number_of_listings. Moreover, there's also an index on any association we join between.

Any idea on how to improve this?

Try the following query

select distinct `accounts`.`id`, `accounts`.`number_of_listings` as alias_0
from `accounts`
left outer join `revenue_item_account_leads`
    on `revenue_item_account_leads`.`account_id` = `accounts`.`id`
    and revenue_item_account_leads.platform_id = 6
left outer join `matches`
    on  `matches`.`matchable_id` = `accounts`.`id`
    and `matches`.`matchable_type` = 'Account'
    and matches.matched_matchable_id in (14, 31, 37)
    and and matches.score >= 0.75
where `accounts`.`locale_id` = 1
    and accounts.number_of_listings > 0
    and revenue_item_account_leads.platform_id is null
    and matches.matched_matchable_id is null
order by `accounts`.`number_of_listings` desc LIMIT 25 OFFSET 0

And these indexes:

accounts(locale_id, number_of_listings, id)
revenue_item_account_leads(account_id, platform_id)
matches(matchable_id, matchable_type, matched_matchable_id, score)

Depending on your relations and data you might not even need the DISTINCT keyword.

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