分组连接查询结果

时间:2013-02-07 06:50:11

标签: mysql join group-by

我正在尝试编写一个查询,向我显示所有订单及其选项。到目前为止已完成,但当我尝试按订单ID对它们进行分组时,它只为每个选项打印一个单独的行,而不是订单ID及其下的所有选项。

我遗失了一些东西,但无法弄清楚它是什么:)

这就是我所拥有的

$sql = 'SELECT *
        FROM `order` RIGHT JOIN `order_option`
        on order.order_id=order_option.order_id
        where order_status_id = 2 
        group by order_option.order_option_id';

$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
    print "ID:{$row['order_id']}  <br> ".
         "OPTION NAME: {$row['name']} <br> ".
         "VALUE: {$row['value']} <br> ".
         "--------------------------------<br>";
} 
echo "Fetched data successfully\n";
mysql_close($conn);

?>

**UPDATE 1**

这就是查询现在的工作方式

SELECT 
  o.order_id, 
  o.name, 
  o.value, 
  GROUP_CONCAT(o.order_id, o.name, o.value SEPARATOR ',') AS Options 
FROM `order_option` AS o 
LEFT JOIN `order` AS oo on o.order_id = oo.order_id 
where oo.order_status_id = 2 
group by o.order_id

1 个答案:

答案 0 :(得分:1)

您应该GROUP BY order_id而使用GROUP_CONCAT来获取同一行中订单的所有选项:

SELECT 
  o.order_id,
  GROUP_CONCAT(oo.order_option_id SEPARATOR ',') AS Options
FROM `order` AS o
RIGHT JOIN `order_option` AS oo on o.order_id = oo.order_id
where o.order_status_id = 2 
group by o.order_id;

SQL Fiddle Demo

如果GROUP_CONCAT不是您要查找的内容,那么您必须使用其他聚合函数,但不要包含GROUP BY子句中不在SELECT子句中的任何列没有聚合函数的子句。否则你会得到不一致的数据。


更新1

您的查询不起作用的原因:

SELECT 
  o.order_id, 
  o.name, 
  o.value, 
  GROUP_CONCAT(o.order_id SEPARATOR ',') AS Options 
FROM order_option AS o 
LEFT JOIN order AS oo on o.order_id = oo.order_id 
where oo.order_status_id = 2 
group by o.order_id

因为o.name, o.value子句中的两列SELECT都不在聚合函数中而不在GROUP BY子句中,所以你得到的这些两列的值不一致,MySQL得到了他们的任意值。试试这个:

SELECT 
  o.order_id, 
  o.name, 
  o.value, 
  GROUP_CONCAT(o.order_id SEPARATOR ',') AS Options 
FROM order_option AS o 
LEFT JOIN order AS oo on o.order_id = oo.order_id 
where oo.order_status_id = 2 
group by o.order_id, 
         o.name,
         o.value;