简体   繁体   中英

How to calculate SUM() of products _qty of WordPress order_itemmeta in MYSQL

I have such complicated MySQL query:

SELECT im.order_item_id, im.meta_key, im.meta_value
FROM `wp_woocommerce_order_itemmeta` AS im
JOIN `wp_woocommerce_order_items` AS oi
ON oi.order_item_id = im.order_item_id
JOIN `wp_posts` AS p
ON p.ID = oi.order_id
WHERE oi.order_id IN (
    SELECT DISTINCT order_id
    FROM wp_tss_orders_history
    WHERE created BETWEEN 1477880000 AND 1689198400
)
AND im.meta_key IN ("_product_id", "_qty")
AND p.post_status <> "trash"
AND oi.order_item_type = "line_item"
ORDER BY im.order_item_id ASC

Which returns such result:查询结果

Is there any way to modify my query (GROUP BY + SUM()) to get result in such format:

array(
  array('_product_id' => 178, '_qty' => 150),
  array('_product_id' => 177, '_qty' => 20),
  array('_product_id' => some other ID, '_qty' => Number Of Items Sold),
)

I've written solution on PHP:

$result = $wpdb->get_results($query);
$stage1= [];
foreach ($result as $data) {
    $stage1[$data->order_item_id][$data->meta_key] = $data->meta_value;
}
$products_count = [];
foreach ($stage1 as $info) {
    $products_count[$info['_product_id']] += intval($info['_qty']);
}

This code returns:

Array (
   [178] => 634
   [177] => 135
   // where key: _product_id => value: sum of _qty for this _product_id
   ...
)

But any thoughts about MySQL solution are welcome. Thanks!

Well all the additional filteres can be ignored at least for me, when trying to add some example how it could look like, because all the data needed for your result example is already in wp_woocommerce_order_itemmeta . As far as i see in your questions you want to get the total quantity of an product_id over ALL order items.

I didn't test this yet but what you need could look something like this:

SELECT metamain.meta_value as product_id,
(
    SELECT SUM(metasub.meta_value) FROM wp_woocommerce_order_itemmeta as metasub
        LEFT JOIN wp_woocommere_order_itemmeta as metajoin 
            ON metajoin.order_item_id=metasub.order_item_id AND metajoin.meta_key='_product_id'
        WHERE metasub.meta_key='_qty' AND metajoin.meta_value=metamain.meta_value
) as qty_sum
 FROM wp_woocommerce_order_itemmeta as metamain 

WHERE metamain.meta_key='_product_id' GROUP BY metamain.meta_value;

well, like i wrote, i didn't test this query yet, and it could still be a lot optimized. First of all it will take very very long to complete because of this huge subselect, so don't use it like this if you want more then just run it manually to get the results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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