select with 2 x sub查询返回重复结果-如何修复?

zbdgwd5y  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(301)

我有这个代码,它结合了订单的细节,并给你一个产品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              |
----------------------------------

如果订单中只有一个项目,如果有多个项目(记录),如果我将第一个select更改为select*,则工作正常,结果如下:

----------------------------------
| 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                |
----------------------------------

我认为这是因为每个子查询的结果被合并,但不能得到上面所期望的结果。怎么做?

von4xj4u

von4xj4u1#

不知怎么的,我觉得你想要这样的东西:

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

相关问题