我制作了一个运行两个查询的程序:一个查询贷方金额,第二个查询借方金额和未偿还的退货。
我已经为这些查询制定了一个程序。它返回相同的结果,但比简单查询花费的时间长五倍。
为什么程序需要更多时间?我读过程序比简单查询更快。
我的简单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.";
}