使用php雄辩和sqlserver进行查询需要很长时间

时间:2018-09-03 15:56:51

标签: php sql-server laravel eloquent

SQL Server中使用PHP时遇到一些问题,我的代码中包含此查询。

  Api::$eloquent->connection('cis')->select("
    SELECT
        SUM (DET.Peso_Salida) AS total,
      CLI.[Codigo Grupo] AS grupo
    FROM
        BNF2.SECO_DEVOLUCION_DETALLE AS DET
    INNER JOIN BNF2.SECO_DEVOLUCION_MAESTRO AS MAS ON DET.Correlativo_Maestro = MAS.Correlativo_Maestro AND MAS.Codigo_Cosecha=:co1
    INNER JOIN BNF.DETALLES_GENERALES_PESOS_2 AS REC ON DET.Numero_Lote=REC.Numero_Lote AND REC.Codigo_Cosecha=:co2
    INNER JOIN BNF.V_CLIENTES_CON_GRUPO AS CLI ON REC.Codigo_Entidad_Cliente_Actual= CLI.Codigo
    GROUP BY CLI.[Codigo Grupo]  
    ", [':co1' => $this->cosecha, ':co2' => $this->cosecha]);

查询用时15秒,SQL Server用100%CPU,现在,如果我删除代码中的参数,查询将很快花费103ms,所以我不明白为什么参数是放慢查询速度

Api::$eloquent->connection('cis')->select("
SELECT
    SUM (DET.Peso_Salida) AS total,
  CLI.[Codigo Grupo] AS grupo
FROM
    BNF2.SECO_DEVOLUCION_DETALLE AS DET
INNER JOIN BNF2.SECO_DEVOLUCION_MAESTRO AS MAS ON DET.Correlativo_Maestro = MAS.Correlativo_Maestro AND MAS.Codigo_Cosecha=9
INNER JOIN BNF.DETALLES_GENERALES_PESOS_2 AS REC ON DET.Numero_Lote=REC.Numero_Lote AND REC.Codigo_Cosecha=9
INNER JOIN BNF.V_CLIENTES_CON_GRUPO AS CLI ON REC.Codigo_Entidad_Cliente_Actual= CLI.Codigo
GROUP BY CLI.[Codigo Grupo]
", []);

运行得很好,有什么主意吗?

1 个答案:

答案 0 :(得分:0)

您应该使用参数化查询或存储过程。

导致查询性能下降的原因可能很多,只有Table info(包括数据类型和长度)和Query Plan才能显示出来。

索引就是其中之一。

由于您的问题就像"when using variable then query is slow. Query perform ok with constant value"

几天前,我们讨论了类似的事情。

Variables make query performance worse