2017-04-09 92 views
0

我們有一個使用跨表和order_by的連接的複雜查詢。下面MySQL order_by optimization

樣品:

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 

WITHOUT在1秒內完成ORDER_BY查詢。 查詢WITH order_by在5秒內完成(使其在生產中無法使用)。

accounts.number_of_listings上已經有一個索引。此外,還有一個關於我們之間加入的任何關聯的索引。

有關如何改善這一點的任何想法?

+0

請提供'EXPLAIN SELECT ...'和'SHOW CREATE TABLE' –

回答

0

嘗試以下查詢

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 

而且這些指標:

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

根據你的關係和數據你可能甚至不需要DISTINCT關鍵字。