为什么我存储的MySQL程序如此之慢?

时间:2012-06-22 11:44:27

标签: php mysql stored-procedures pagespeed

我制作了一个程序,该程序运行两个查询:一个用于信用额度,另一个用于借记金额并且返回未付款。

我为这些查询制作了一个程序。它返回了相同的结果,但比简单查询要长五倍。

为什么程序需要更多时间?我已经读过,程序比简单的查询更快。

我的简单php方法

function getOutStandingBalance($OID)
{
    $strSQL  = "select sum(amount) from t where isdeleted=0 and iscredit=1 and oid='1212'";
    $Result1 = $this->ADb->ExecuteQuery($strSQL);

    $CreditSum = $Result1->fields[0];

    $strSQL  = "select sum(amount) from t where isdeleted=0 and iscredit=0 and oid='1212'";     $Result2 = $this->ADb->ExecuteQuery($strSQL);

    $DebitSum = $Result2->fields[0];

    $OutStandingBalance = sprintf("%2.2f",$CreditSum - $DebitSum);
    echo $OutStandingBalance;
}

我的程序

DELIMITER $$

CREATE PROCEDURE `getOutStandingBalance`(OUT Total DECIMAL(16,2),IN OID INT)
    DETERMINISTIC
    COMMENT 'A procedure'
BEGIN
    DECLARE Credit DECIMAL(16,2);
    DECLARE Debit  DECIMAL(16,2);
    SELECT SUM(t.Amount) INTO Credit FROM `t` WHERE t.IsDeleted=0 AND t.IsCredit=1 AND t.OID=OID;

    SELECT SUM(t.Amount) INTO Debit FROM `t` WHERE t.IsDeleted=0 AND t.IsCredit=0 AND t.OID=OID;

    SET Total = IFNULL(Credit, 0) - IFNULL(Debit, 0);
END$$

DELIMITER ;

PHP脚本使用过程调用和简单的php查询调用基准测试

$begin = microtime(true);
$chkAmount      = $myTransaction->getOutStandingBalance(1212);
echo $chkAmount;
echo "<br />";
$end = microtime(true); 
echo "Time taken for normal:", $end - $begin;
$norml = $end - $begin;
echo "<br />";
echo "<br />";
$begin = microtime(true);
$stmt = "CALL getOutStandingBalance(@Total,1212)";
$rsstmt = "SELECT @Total;";
$rs = $myADb->Execute($stmt);
$rsstmt = $myADb->Execute($rsstmt);
echo $rsstmt->fields[0];
echo "<br />";
$end = microtime(true); 
echo "Time taken for Procedure:", $end - $begin; 

$procd = $end - $begin;

if($norml>$procd)
{
    echo "<br> Procedure is Fast.";
}
else
{
    echo "<br> Normal Query is Fast.";
}

0 个答案:

没有答案