MySQL优化排序
我们有一个复杂的查询,它使用跨表的联接和order_by 样本如下:MySQL优化排序,mysql,sql-order-by,Mysql,Sql Order By,我们有一个复杂的查询,它使用跨表的联接和order_by 样本如下: 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
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
选择不同的“帐户”。`id`,
`帐户`.`number\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
从`账户`
在`收入`项目`账户`线索'上左外联接`收入`项目`账户`线索'。`account ` id`=`accounts`.`id`
“matches”上的左外部联接“matches”。“matchable_id”=`accounts`.`id`
和'matches'。'matcheable_type`='Account'
其中`accounts`.`locale\u id`=1
及(
收入\项目\帐户\潜在客户。平台\ id为空
或(收入、项目、账户、潜在客户、平台、id!=6)
)
及(
matches.matched\u matcheable\u id为空
或(
matches.matched_matcheable_id in(14,31,37)
和比赛。得分<0.75
)
或者(matches.matched_matcheable_id不在(14,31,37))
)
和(accounts.number of_listings>0)
按“帐户”排序。“列表数量”描述限制25偏移量0
没有order_by的查询将在1秒内完成。
带有order_by的查询在5秒内完成(使其无法在生产中使用)
accounts.number\u列表上已经有索引。此外,还有一个关于我们之间任何关联的索引
你知道如何改进吗 尝试以下查询
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
关键字。请提供EXPLAIN SELECT…
和SHOW CREATE TABLE