我在使用PDO / MySQL,php 7.0和mysql 5.5按月获取累计金额时遇到一些问题。
通过多个查询,我收到了“ 百分比:SQLSTATE [HY000]:常规errorvar ”作为错误。如果我删除了这些“ SET”行,它就会消失,但是我无法做我想做的事情。
$sql = "
SET @accInc := 0;
SET @accOut := 0;
SELECT
q1.y as year,
q1.m as month,
(@accInc := @accInc + q1.income) AS accInc,
(@accOut := @accOut + q1.outgo) AS outInc
FROM
(SELECT
YEAR(`date`) AS y,
MONTH(`date`) AS m,
SUM(CASE WHEN amount > 0 THEN amount ELSE 0 END) as income,
SUM(CASE WHEN amount < 0 THEN amount ELSE 0 END) as outgo
FROM `transaction`
GROUP BY y, m
ORDER BY y, m
) AS q1";
require("./pdo.php");
try {
$req = $db->prepare($sql);
$req->execute();
$data = $req->fetchAll(PDO::FETCH_ASSOC);
foreach($data as $row) {
$acc[$row["year"]][$row["month"]] = array(
"inc" => (float)$row["accInt"],
"out" => (float)$row["accOut"]
);
}
} catch(PDOException $except) {
printf("Excention : %s", $except->getMessage());
}
谢谢。
编辑:我必须设置$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
并隔离SET
命令。现在可以了。