简体   繁体   English

在JOIN中重写慢的SQL(子)查询

[英]Rewriting a slow SQL (sub) query in JOIN

So I've got massive slow SQL query and I've narrowed it down to a slow sub-query, so I want to rewrite it to a JOIN. 因此,我有大量的慢速SQL查询,并将其缩小为慢速子查询,因此我想将其重写为JOIN。 But I'm stuck... (due to the MAX and GROUP BY ) 但是我被卡住了...(由于MAXGROUP BY

SELECT *
FROM local.advice AS aa
  LEFT JOIN webdb.account AS oa ON oa.shortname = aa.shortname 
WHERE aa.aa_id = ANY (SELECT MAX(dup.aa_id)
                      FROM local.advice AS dup
                      GROUP BY dup.shortname) 
  AND oa.cat LIKE '111'
ORDER BY aa.ram, aa.cpu DESC
LIMIT 0, 30

Here is a different version of your query where the subquery is converted with a join clause 这是查询的不同版本,其中子查询使用连接子句进行转换

select * from local.advice aa 
JOIN webdb.account oa ON oa.shortname = aa.shortname 
join(
 select max(aa_id) as aa_id,shortname from local.advice 
 group by shortname
)x on x.aa_id = aa.aa_id
where
oa.cat = '111'
order by aa.ram, aa.cpu DESC 
limit 0,30

Also you may need to apply indexes if they are not added already 另外,如果尚未添加索引,则可能需要应用索引

alter table local.advice add index shortname_idx(shortname);
alter table webdb.account add index cat_shortname_idx(cat,shortname);
alter table local.advice add index ram_idx(ram);
alter table local.advice add index cpu_idx(cpu);

I am assuming aa_id is a primary key so did not add the index 我假设aa_id是主键,所以没有添加索引

Make sure to take a backup of the tables before applying the indexes 在应用索引之前,请确保对表进行备份

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM