-2

我构建了以下查询:

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 Fiddle。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 秒,并且在此之前我需要它的程序超时。我根据@Bluefeet 的建议创建了一个索引,并将其命名为 Zones,并将 GVA14.COD_ZONA 包含在其中。

接下来我该怎么做?

4

3 回答 3

2

WHERE子句上的过滤器移至JOIN条件。如果您将过滤器留在WHERE子句中,则查询的作用类似于 anINNER JOIN而不是 a 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

结果:

| COD_ZONA | SUMOFIMPORTE |
---------------------------
|       01 |         3000 |
|       02 |         1000 |
|       03 |            0 |
于 2013-01-08T10:28:24.997 回答
1

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

于 2013-01-08T14:07:00.207 回答
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;
于 2013-01-08T10:26:18.267 回答