查询运行速度很慢

时间:2016-11-08 10:35:40

标签: mysql

我的查询运行速度非常慢。查询的目标是列出表artikli中表和数量的所有文章。然后我想看到另一个表格中列出的文章销售情况(今年为artikli_2016,上一年为artikli_2015)

SELECT a.artid,
   a.artsifra,
   a.artnaziv,
   a.artstanje,
   a.artstanjepalete,
   ( a.artstanje + a.artstanjepalete ) AS total,
   Sum(g.izlaz)                        AS promet,
   c.jmoznaka,
   Sum(f.izlaz)                        AS promet
FROM   artikli a
       LEFT JOIN artikli_2016 g
              ON a.artid = g.artikal
       LEFT JOIN artikli_2015 f
              ON a.artid = f.artikal
       LEFT JOIN jed_mjere c
              ON a.artmjera = c.jmid
WHERE  a.artroditelj != 0
       AND a.artaktivan
GROUP  BY a.artid
ORDER  BY a.artid ASC 

一旦我加入artikli_2015,它变得非常缓慢。如果有人能给我一个建议或解决方案来更快地运行查询,那将是非常有帮助的。

1 个答案:

答案 0 :(得分:1)

由于有2个多个记录(我怀疑),你可能需要使用几个子查询来获得总和。假设jed_mjere每个ArtMjera最多只有1条记录。

SELECT a.ArtId, 
        a.ArtSifra, 
        a.ArtNaziv,
        a.ArtStanje,
        a.ArtStanjePalete, 
        (a.ArtStanje + a.ArtStanjePalete) as total, 
        g.promet,
        c.JmOznaka,
        f.promet
FROM artikli a 
LEFT OUTER JOIN 
(
    SELECT Artikal, SUM(Izlaz) AS promet
    FROM artikli_2016
    GROUP BY Artikal
)   g 
ON a.ArtId = g.Artikal 
LEFT OUTER JOIN 
(
    SELECT Artikal, SUM(Izlaz) AS promet
    FROM artikli_2015
    GROUP BY Artikal
)   f 
ON a.ArtId = f.Artikal 
LEFT OUTER JOIN jed_mjere c ON a.ArtMjera = c.jmid 
WHERE a.ArtRoditelj != 0 
AND a.ArtAktivan 
ORDER BY a.ArtId ASC

如果您的查询仅处理来自artikli的少量记录(即 a.ArtRoditelj!= 0且a.ArtAktivan 排除大多数行),则可能值得进行连接以排除记录子查询。

SELECT a.ArtId, 
        a.ArtSifra, 
        a.ArtNaziv,
        a.ArtStanje,
        a.ArtStanjePalete, 
        (a.ArtStanje + a.ArtStanjePalete) as total, 
        g.promet,
        c.JmOznaka,
        f.promet
FROM artikli a 
LEFT OUTER JOIN 
(
    SELECT g.Artikal, SUM(g.Izlaz) AS promet
    FROM artikli a 
    INNER JOIN artikli_2016 g
    ON a.ArtId = g.Artikal 
    WHERE a.ArtRoditelj != 0 
    AND a.ArtAktivan 
    GROUP BY g.Artikal
)   g 
ON a.ArtId = g.Artikal 
LEFT OUTER JOIN 
(
    SELECT f.Artikal, SUM(f.Izlaz) AS promet
    FROM artikli a 
    INNER JOIN artikli_2015 f
    ON a.ArtId = g.Artikal 
    WHERE a.ArtRoditelj != 0 
    AND a.ArtAktivan 
    GROUP BY f.Artikal
)   f 
ON a.ArtId = f.Artikal 
LEFT OUTER JOIN jed_mjere c ON a.ArtMjera = c.jmid 
WHERE a.ArtRoditelj != 0 
AND a.ArtAktivan 
ORDER BY a.ArtId ASC