这是sql:
$sql = "SELECT DISTINCT o.order_id, cgd.name as customer_group, CONCAT(o.firstname, ' ', o.lastname) AS customer_name,
email, telephone, payment_firstname, payment_lastname, payment_address_1, payment_address_2, payment_city, payment_zone, payment_postcode, GROUP_CONCAT(DISTINCT op.name) as prod_name, op.model as prod_model, GROUP_CONCAT(op.quantity) as prod_quantity,
CONCAT(o.shipping_firstname, ' ', o.shipping_lastname,',',o.shipping_address_1,',',o.shipping_address_2,',', o.shipping_city,'-',o.shipping_postcode) AS shipping_address,
o.payment_method, o.shipping_method, o.total, o.currency_code,o.currency_value,
o.date_added, oos.name as order_status, o.custom_field as agentcode
FROM oc_order o
LEFT JOIN oc_customer_group_description cgd ON (o.customer_group_id = cgd.customer_group_id)
LEFT JOIN oc_order_product op ON (o.order_id = op.order_id)
LEFT JOIN oc_order_status oos ON (o.order_status_id = oos.order_status_id) WHERE cgd.language_id = 1 GROUP BY o.order_id";
我有一个数据库,其结果具有相同ID的不同数组
Array ( [order_id] => 1 [prod_name] => prod1 [qty] => 1)
Array ( [order_id] => 1 [prod_name] => prod2 [qty] => 1)
Array ( [order_id] => 2 [prod_name] => prod1 [qty] => 1)
Array ( [order_id] => 3 [prod_name] => prod1 [qty] => 1)
我希望上面合并为:
Array ( [order_id] => 1 [prod_name] => prod1,prod2 [qty] => 1,1)
Array ( [order_id] => 2 [prod_name] => prod1 [qty] => 1)
Array ( [order_id] => 3 [prod_name] => prod1 [qty] => 1)
在我添加GROUP_CONCAT后,它会输入:
Array ( [order_id] => 1 [prod_name] => prod1,prod1,prod2,prod2 [qty] => 1,1,1,1)
Array ( [order_id] => 2 [prod_name] => prod1 [qty] => 1)
Array ( [order_id] => 3 [prod_name] => prod1 [qty] => 1)
数据库结构是:
o (order):
1 order_id int(11) Primary Primary
op (order_product):
1 order_product_id int(11)
2 order_id int(11)
3 product_id int(11)
4 name varchar(255)
5 quantity int(4)
6 price decimal(15,4)
7 total decimal(15,4)
cgd (customer_group_description):
1 customer_group_id int(11)
2 language_id int(11)
3 name varchar(32)
4 description text
答案 0 :(得分:0)
在php中你可以循环执行:
$merge_arr = [];
foreach( $arr as $key => $row){
if( isset( $merge_arr[ $row['order_id'] ] ) ) {
$merge_arr[ $row['order_id'] ][ 'order_id' ] .= "," . $arr[ $key ][ 'prod_name' ];
$merge_arr[ $row['order_id'] ][ 'prod_name' ] .= "," . $arr[ $key ][ 'prod_name' ];
$merge_arr[ $row['order_id'] ][ 'qty' ] ,= "," $arr[ $row['order_id'] ][ 'qty' ];
} else {
$merge_arr[ $row['order_id'] ][ 'prod_name' ] = $arr[ $row['order_id'] ][ 'prod_name' ];
$merge_arr[ $row['order_id'] ][ 'qty' ] = $arr[ $row['order_id'] ][ 'qty' ];
}
}
SQL中的:
SELECT order_id, GROUP_CONCAT(prod_name), GROUP_CONCAT(qty)
FROM your_table
GROUP_BY order_id
如果可以,请使用更快的SQL解决方案。
你的数据库结构是这样的吗? (在一个简单的版本中)
o (order):
order_id PK
order_status_id FK
customer_group_id FK
op (order_product):
order_product_id PK
order_id FK
quantity
os (order_status):
order_status_id PK
cgd (customer_group_description):
customer_group_id PK