简体   繁体   English

用PHP将MySQL结果分组

[英]Group MySQL results with PHP

I am having the following script that takes the results from 3 tables based on a field called "order_id" in all tables. 我有以下脚本,该脚本根据所有表中名为“ order_id”的字段从3个表中获取结果。

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

$result = mysql_query($sql); 
while($row = mysql_fetch_assoc($result))
 {
$options=$row['Options'];
print "|$options|";

    PRINT "<br>-------------------<br>";
} 

The problem is that in table "order_option" there are 2 or more rows with options for each order_id. 问题是在表“ order_option”中有2个或更多行,每个order_id都有选项。

The results printed by the script is: 脚本打印的结果是:

ID, Model, option1:Value, ID, Model, option2:Value ID,型号,选项1:值, ID,型号,选项2:值

And what I need is: 我需要的是:

ID, MODEL, OPTION1:Value, OPTION2:Value ID,MODEL,OPTION1:值,OPTION2:值

So, no duplication of ID and MODEL for every row. 因此,每一行都没有ID和MODEL的重复。

Any suggestions how can I achieve that? 有什么建议可以实现吗?

The problem is with how you're implementing GROUP_CONCAT . 问题在于您如何实现GROUP_CONCAT You have 2 rows in your Order_Option table that have different options with the same option id. 您的Order_Option表中有2行,具有相同选项ID的不同选项。 Something like: 就像是:

OrderId    Name     Value
1          Option1  Value1 
1          Option2  Value2

Using GROUP_CONCAT(OrderId, Name, Value) will concatenate all those fields like: 使用GROUP_CONCAT(OrderId,Name,Value)将连接所​​有这些字段,例如:

1, Option1, Value1, 1, Option2, Value2

Instead, you want to retrieve your OrderId on it's own: 相反,您想自己检索OrderId:

SELECT OrderId, GROUP_CONCAT(Name, Value)...

This will give you: 这将为您提供:

1, Option1, Value1, Option2, Value2

And then the rest is just in your presentation logic. 然后剩下的就是您的演示逻辑。

Good luck. 祝好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM