优化这个慢的mysql查询

时间:2016-08-02 12:22:13

标签: mysql left-join query-optimization inner-join

SELECT SUM( a.situacao =2 OR a.situacao =0 ) AS cotacoes, 
       SUM( a.situacao =1 ) AS n_publicar, 
       SUM( a.inicio <= NOW( ) AND DATE_ADD( a.inicio, INTERVAL a.duracao HOUR ) >= NOW( ) AND a.situacao =2 ) AS disputa, 
       SUM( a.inicio > NOW( ) AND a.situacao =2 ) AS agendados, 
       SUM( DATE_ADD( a.inicio, INTERVAL a.duracao HOUR ) <= NOW( ) AND a.situacao =2 AND a.id_vencedor = -2 ) AS analise, 
       SUM( a.prazoi > NOW( ) AND a.situacao =2 AND a.id_vencedor >0 ) AS aguardando_execucao, 
       SUM( a.situacao =0 ) AS cancelados, 
       SUM( DATE_ADD( a.inicio, INTERVAL a.duracao HOUR ) <= NOW( ) AND a.situacao =2 AND a.id_vencedor = -3 ) AS fracassados, 
       SUM( a.prazot < NOW( )  AND a.situacao =2 AND a.id_vencedor >0 AND ( b.id_avaliacao IS NULL  OR b.id_avaliacao =  '' ) ) AS avaliacao, 
       SUM( a.situacao =2 AND a.id_vencedor >0 AND a.prazot > NOW( )  AND a.prazoi <= NOW( ) ) AS execucao 
FROM leilao_pregoes a 
LEFT JOIN leilao_avaliacao b ON a.id_pregao = b.id_pregao AND b.situacao = 1
INNER JOIN leilao_edital c ON a.id_edital = c.id_edital 
WHERE c.id_comprador =1

我知道这可以改善......

2 个答案:

答案 0 :(得分:0)

我想知道COUNT在可行的情况下会更快。

主要的改进是将列作为记录获取:

cotacoes    123
n_publicar   456
...

SELECT 'cotacoes', SUM(...)
...
UNION SELECT 'n_publicar', SUM(...)
...

原因是条件部分排除,加入可以更好地利用。

然后你可以分别处理最慢的SELECT。你可以在子查询中进行并行查询。

答案 1 :(得分:0)

LEFT JOIN leilao_avaliacao b ON a.id_pregao = b.id_pregao AND b.situacao = 1

leilao_avaliacao以任意顺序需要INDEX(id_pregao, situacao)

INNER JOIN leilao_edital c ON a.id_edital = c.id_edital
WHERE c.id_comprador =1

leilao_edital需要INDEX(id_comprador, id_edital)以任何顺序

如需进一步讨论,请提供SHOW CREATE TABLE,并向我们提供表格有多大的提示。