我当前有两个表。我想在一个查询中检索订单的所有相应行。
我当前的代码如下:
$query = '
SELECT * FROM table_a
JOIN table_b ON table_b.order_id = table_a.order_id
WHERE table_a.order_id = '1'
GROUP BY table_a.order_id
';
$result_prepare = $this->DB->prepare($query);
$result_prepare->execute();
$result = $result_prepare->fetchAll(PDO::FETCH_ASSOC);
$query_result = array('result'=>$result);
print_r($query_result);
输出结果仅返回THE FIRST ROW:
Array
(
[0] => Array
(
[order_id] => 1
[row_id] => 1
[value] => 100
)
}
我希望输出结果返回按行分组的所有行。
Array
(
[0] => Array
(
[order_id] => 1
[rows] => Array
(
[0] => Array
(
[row_id] => 1
[value] => 100
)
[1] => Array
(
[row_id] => 2
[value] => 101
)
)
)
}
我怎样才能实现这个目标?我需要更改我的 SQL 查询。
最佳答案
您的单行是 MySQL 处理 GROUP BY
的结果,缺少任何聚合函数,例如 COUNT(),SUM(),MIN(),MAX()
。它将组折叠为单行,并且未分组的列的值不确定,因此不值得依赖。
但是,如果您想要一个由 order_id
索引的数组结构,则不需要 GROUP BY
。相反,执行一个简单的查询,然后在您的 PHP 代码中,在循环中将其重组为您要查找的格式。
// join in table_a if you need more columns..
// but this query is doable with table_b alone
$query = "
SELECT
order_id,
row_id,
value
FROM table_b
WHERE order_id = '1'
";
// You do not actually need to prepare/execute this unless you
// are eventually going to pass order_id as a parameter
// You could just use `$this->DB->query($query) for the
// simple query without user input
$result_prepare = $this->DB->prepare($query);
$result_prepare->execute();
$result = $result_prepare->fetchAll(PDO::FETCH_ASSOC);
// $result now is an array with order_id, row_id, value
// Loop over it to build the array you want
$final_output = array();
foreach ($result as $row) {
$order_id = $row['order_id'];
// Init sub-array for order_id if not already initialized
if (!isset($final_output[$order_id])) {
$final_output[$order_id] = array();
}
// Append the row to the sub-array
$final_output[$order_id][] = array(
'row_id' => $row['row_id'],
'value' => $row['value']
);
// You could just append [] = $row, but you would still
// have the order_id in the sub-array then. You could just
// ignore it. That simplifies to:
// $final_output[$order_id][] = $row;
}
// Format a little different than your output, order_id as array keys
// without a string key called order_id
print_r($final_output);
关于php - MySQL 组按 : How to return multiple rows?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21783728/