这是我的代码:
$sql = "
SET @run_balqty :=0;
SELECT
transaction_date,
item_id,
item_description,
unit_id,
quantity,
( @run_balqty := @run_balqty + quantity ) AS balance_qty,
reference_code
FROM
`report_ledger` AS ledger
WHERE
item_id = 3147
ORDER BY
transaction_date ";
$query = Yii::$app->db->createCommand($sql)->queryAll();
当我尝试运行此代码时。我收到错误。
SQLSTATE [HY000]:常规错误
现在..我的问题是:为什么我会收到此错误?我该如何让它运行?
需要帮助。感谢。
答案 0 :(得分:3)
您正在尝试获取包含命令(SET @run_balqty :=0
)的查询结果,该命令不是“可获取的”。您必须先单独执行该命令,然后可以将queryAll()
调用到SELECT
查询命令:
Yii::$app->db->createCommand("SET @run_balqty :=null;")->execute();
$sql = "
SELECT
transaction_date,
item_id,
item_description,
unit_id,
quantity,
( @run_balqty := @run_balqty + quantity ) AS balance_qty,
reference_code
FROM
`report_ledger` AS ledger
WHERE
item_id = 3147
ORDER BY
transaction_date ";
$query = Yii::$app->db->createCommand($sql)->queryAll();
P.S。:小心使用SET
语句,阅读this。