我有下面的查询,它返回 OrderID、order_item_id、_product_id、Quantity。
SELECT `wp_woocommerce_order_items`.`order_id` AS 'OrderID',
`wp_woocommerce_order_items`.`order_item_id`,
MAX(CASE WHEN `wp_woocommerce_order_itemmeta`.`meta_key` = '_product_id' THEN `wp_woocommerce_order_itemmeta`.`meta_value` ELSE NULL END) AS '_product_id',
MAX(CASE WHEN `wp_woocommerce_order_itemmeta`.`meta_key` = '_qty' THEN `wp_woocommerce_order_itemmeta`.`meta_value` ELSE NULL END) AS 'Quantity'
FROM `wp_woocommerce_order_items`, `wp_woocommerce_order_itemmeta`
WHERE `wp_woocommerce_order_items`.`order_id` = 50
AND `wp_woocommerce_order_items`.`order_item_id` = `wp_woocommerce_order_itemmeta`.`order_item_id`
AND `wp_woocommerce_order_items`.`order_item_type` = 'line_item'
AND (`wp_woocommerce_order_itemmeta`.`meta_key` = '_qty'
OR `wp_woocommerce_order_itemmeta`.`meta_key` = '_product_id')
GROUP BY `wp_woocommerce_order_items`.`order_item_id`
回报:
+---------+---------------+-------------+----------+
| OrderID | order_item_id | _product_id | Quantity |
+---------+---------------+-------------+----------+
| 50 | 11 | 27 | 3 |
| 50 | 18 | 42 | 1 |
+---------+---------------+-------------+----------+
然后,我循环遍历上述结果中的每一行,以便在 php 中使用以下查询中的 _product_id 进行匹配wp_postmeta
。post_id
.
SELECT `post_id`,
MAX(CASE WHEN `wp_postmeta`.`meta_key` = '_sku' THEN `wp_postmeta`.`meta_value` ELSE NULL END) AS 'PartNumber',
MAX(CASE WHEN `wp_postmeta`.`meta_key` = '_price' THEN `wp_postmeta`.`meta_value` ELSE NULL END) AS 'UnitPrice'
FROM `wp_postmeta`
WHERE `wp_postmeta`.`post_id` = $PRODUCT_ID
AND (`wp_postmeta`.`meta_key` = '_sku'
OR `wp_postmeta`.`meta_key` = '_price')
回报:
+---------+------------+-----------+
| post_id | PartNumber | UnitPrice |
+---------+------------+-----------+
| 27 | MOO123 | 50 |
+---------+------------+-----------+
+---------+------------+-----------+
| post_id | PartNumber | UnitPrice |
+---------+------------+-----------+
| 42 | MOO345 | 145 |
+---------+------------+-----------+
有没有办法将两者结合起来,所以它会添加PartNumber
到UnitPrice
第一个查询结果并返回如下数据?
+---------+---------------+-------------+----------+------------+-----------+
| OrderID | order_item_id | _product_id | Quantity | PartNumber | UnitPrice |
+---------+---------------+-------------+----------+------------+-----------+
| 50 | 11 | 27 | 3 | MOO123 | 50 |
| 50 | 18 | 42 | 1 | MOO345 | 145 |
+---------+---------------+-------------+----------+------------+-----------+
表数据在这里找到:http: //pastebin.com/3EN5P4fD
谢谢