MySQL GROUP BY:如何返回多行?

时间:2014-02-14 15:52:34

标签: php mysql pdo

我有两张桌子。我想在一个查询中检索订单的所有相应行。

enter image description here

我目前的代码如下:

$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
        )

}

我希望输出结果按行返回所有行GROUPED。

Array
(
    [0] => Array
        (
            [order_id] => 1
            [rows] => Array
                    (
                        [0] => Array
                            (
                                [row_id] => 1
                                [value] => 100

                            )

                        [1] => Array
                            (
                                [row_id] => 2
                                [value] => 101

                            )

                    )

        )

}

我怎样才能做到这一点?我需要更改我的SQL查询。

3 个答案:

答案 0 :(得分:2)

您的单行是MySQL处理GROUP BY而没有任何聚合函数(如COUNT(),SUM(),MIN(),MAX())的结果。它将组折叠为单行,对于未分组的列具有不确定的值,并且不是可依赖的。

如果您想要一个由GROUP BY索引的数组结构,则不需要order_id。相反,执行一个简单的查询,然后在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);

答案 1 :(得分:0)

我想你想要这个:

$query = '
SELECT * 
FROM table_a
JOIN table_b 
ON table_b.order_id = table_a.order_id
WHERE table_a.order_id = '1'
ORDER BY b.row_id
';

答案 2 :(得分:0)

我认为您需要使用OUTER JOIN语句,而不是GROUP BY。