我有这个代码,它结合了订单详细信息,并为您提供订单商品的产品ID和变体ID。
SELECT (
SELECT meta_value as product_id
FROM ctc_woocommerce_order_itemmeta
LEFT JOIN ctc_woocommerce_order_items ON ctc_woocommerce_order_itemmeta.order_item_id = ctc_woocommerce_order_items.order_item_id
WHERE meta_key = '_product_id'
AND order_id = 3989
) as product_id,
(
SELECT meta_value as variation_id
FROM ctc_woocommerce_order_itemmeta
LEFT JOIN ctc_woocommerce_order_items ON ctc_woocommerce_order_itemmeta.order_item_id = ctc_woocommerce_order_items.order_item_id
WHERE meta_key = '_variation_id'
AND order_id = 3989
) as variation_id
结果如下:
----------------------------------
| product_id | variation_id |
----------------------------------
| 3921 | 3922 |
----------------------------------
如果订单中只有1个项目,如果有多个项目(记录),如果我将第一个SELECT更改为SELECT * FROM,结果是:
----------------------------------
| product_id | variation_id |
----------------------------------
| 17420 | 17422 |
| 17420 | 16963 |
| 17420 | 0 |
| 16961 | 17422 |
| 16961 | 16963 |
| 16961 | 0 |
| 33601 | 17422 |
| 33601 | 16963 |
| 33601 | 0 |
----------------------------------
我期待结果是:
----------------------------------
| product_id | variation_id |
----------------------------------
| 17420 | 17422 |
----------------------------------
| 16961 | 16963 |
----------------------------------
| 33601 | 0 |
----------------------------------
我认为这与每个子查询的结果有关,但无法达到上述预期结果。怎么做?
答案 0 :(得分:0)
不知何故,我想你想要这样的事情:
SELECT MAX(CASE WHEN oim.meta_key = '_product_id' THEN meta_value END) as product_id,
MAX(CASE WHEN oim.meta_key = '_variation_id' THEN meta_value END) as variation_id
FROM ctc_woocommerce_order_itemmeta oim LEFT JOIN
ctc_woocommerce_order_items oi
ON oim.order_item_id = oi.order_item_id
WHERE oi.order_id = 3989 AND oim.meta_key IN ('_product_id', '_variation_id')
GROUP BY oim.order_item_id