在 JOIN 中重写一个慢 SQL (sub) 查询

Rewriting a slow SQL (sub) query in JOIN

所以我有大量缓慢的 SQL 查询,我已将其缩小为一个缓慢的子查询,因此我想将其重写为 JOIN。但是我卡住了...(由于 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

这是您的查询的不同版本,其中子查询使用连接子句进行转换

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

如果尚未添加索引,您可能还需要应用索引

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);

我假设 aa_id 是主键所以没有添加索引

确保在应用索引之前对表进行备份