我运行了以下命令,它确实有效。
$stmt = $pdo->query("
CREATE TEMPORARY TABLE IF NOT EXISTS info AS (
SELECT warehouse.merchandise_id, SUM(warehouse.prod_quantity) AS qty
FROM warehouse
WHERE warehouse.merchandise_id IN (SELECT merchandise.id FROM merchandise)
GROUP BY warehouse.merchandise_id
);
SELECT LPAD(`id`,8,'0'), prod_title, prod_lcode, prod_price, qty
FROM `merchandise` INNER JOIN info
ON merchandise.id = info.merchandise_id;
");
// skip to next rowset, because it's a fatal error to fetch from a statement that has no result
$stmt->nextRowset();
do {
$rowset = $stmt->fetchAll(PDO::FETCH_NUM);
if ($rowset) {
print_r($rowset);
}
} while ($stmt->nextRowset());
请注意,我必须在您的查询中修复merchandise_count.merchandise_id
to info.merchandise_id
,因为您没有对merchandise_count
.
但是,我建议您不要为多查询而烦恼。在一次调用中连接多个 SQL 语句没有任何好处。也不支持在使用多查询时使用准备好的语句,或定义存储例程,如过程、函数或触发器。
相反,一次执行一个语句。exec()
如果语句没有结果集并且不需要准备语句,则使用该语句。
$pdo->exec("
CREATE TEMPORARY TABLE IF NOT EXISTS info AS (
SELECT warehouse.merchandise_id, SUM(warehouse.prod_quantity) AS qty
FROM warehouse
WHERE warehouse.merchandise_id IN (SELECT merchandise.id FROM merchandise)
GROUP BY warehouse.merchandise_id
)");
$stmt = $pdo->query("
SELECT LPAD(`id`,8,'0'), prod_title, prod_lcode, prod_price, qty
FROM `merchandise` INNER JOIN info
ON merchandise.id = info.merchandise_id
");
$rowset = $stmt->fetchAll(PDO::FETCH_NUM);
if ($rowset) {
print_r($rowset);
}
只要使用相同的$pdo
连接,就可以在后续查询中引用临时表。