在图表中添加零值

时间:2013-01-08 10:24:14

标签: mysql

我构建了以下查询:

SELECT GVA14.COD_ZONA, Sum(GVA12.IMPORTE) AS SumOfIMPORTE
FROM GVA14 LEFT JOIN GVA12 
  ON GVA14.COD_CLIENT = GVA12.COD_CLIENT
WHERE Month(GVA12.FECHA_EMIS)=Month(curdate())
AND Year(GVA12.FECHA_EMIS)=Year(curdate())
GROUP BY GVA14.COD_ZONA;

但是我想要显示COD_ZONA中的其他值。如果我把月和年过滤器拿走,那就是这些。对于任何有兴趣的人来说,这是一个SQL小提琴。 http://sqlfiddle.com/#!2/3aae1/3


编辑1#

我现在有以下查询:

SELECT GVA14.COD_ZONA, Coalesce(Sum(GVA12.IMPORTE), 0) AS SumOfIMPORTE
FROM GVA14 
LEFT JOIN GVA12 
  ON GVA14.COD_CLIENT = GVA12.COD_CLIENT
  AND Month(GVA12.FECHA_EMIS)=Month(curdate())
  AND Year(GVA12.FECHA_EMIS)=Year(curdate())
GROUP BY GVA14.COD_ZONA;

但是当我尝试执行它时,需要110秒的aprox和我之前需要它的程序。我已经根据@Bluefeet的建议创建了一个索引,并将其命名为Zones并在其中包含了GVA14.COD_ZONA。

接下来我该怎么做?

3 个答案:

答案 0 :(得分:2)

WHERE子句上的过滤器移至JOIN条件。如果您将过滤器保留在WHERE子句中,则查询就像INNER JOIN而不是LEFT JOIN

SELECT GVA14.COD_ZONA, Coalesce(Sum(GVA12.IMPORTE), 0) AS SumOfIMPORTE
FROM GVA14 
LEFT JOIN GVA12 
  ON GVA14.COD_CLIENT = GVA12.COD_CLIENT
  AND Month(GVA12.FECHA_EMIS)=Month(curdate())
  AND Year(GVA12.FECHA_EMIS)=Year(curdate())
GROUP BY GVA14.COD_ZONA;

请参阅SQL Fiddle with Demo

结果:

| COD_ZONA | SUMOFIMPORTE |
---------------------------
|       01 |         3000 |
|       02 |         1000 |
|       03 |            0 |

答案 1 :(得分:1)

我已经通过在表上添加4个索引(不知道是否有太多!)来解决这个问题。它起作用了......

答案 2 :(得分:0)

    SELECT GVA14.COD_ZONA
         , COALESCE(Sum(GVA12.IMPORTE),0) AS SumOfIMPORTE
      FROM GVA14 
      LEFT 
      JOIN GVA12 
        ON GVA14.COD_CLIENT = GVA12.COD_CLIENT
       AND Month(GVA12.FECHA_EMIS)=Month(curdate())
       AND Year(GVA12.FECHA_EMIS)=Year(curdate())
     GROUP 
        BY GVA14.COD_ZONA;