1

我有以下查询:

SELECT entity_id AS product_id FROM catalog_product_entity cpe
LEFT JOIN cataloginventory_stock_item csi ON csi.product_id = cpe.entity_id
WHERE cpe.type_id = 'configurable'
AND csi.is_in_stock = 0
AND (SELECT SUM(qty) FROM catalog_product_relation cpr LEFT JOIN cataloginventory_stock_item cisi ON cisi.product_id = cpr.child_id WHERE cpr.parent_id = cpe.entity_id) > 0

它返回以下结果:

product_id
-----------
912
906
894
559
364

我正在尝试根据上述查询结果中存在的表的 product_id更新表中的is_in_stock列。cataloginventory_stock_item

我试图做的是:

UPDATE cataloginventory_stock_item
SET is_in_stock = 1
WHERE product_id IN (
    SELECT entity_id AS product_id FROM catalog_product_entity cpe
    LEFT JOIN cataloginventory_stock_item csi ON csi.product_id = cpe.entity_id
    WHERE cpe.type_id = 'configurable'
    AND csi.is_in_stock = 0
    AND (SELECT SUM(qty) FROM catalog_product_relation cpr LEFT JOIN cataloginventory_stock_item cisi ON cisi.product_id = cpr.child_id WHERE cpr.parent_id = cpe.entity_id) > 0
)

我收到以下错误:
You can't specify target table 'cataloginventory_stock_item' for update in FROM clause

我似乎无法弄清楚如何重组查询以使其工作。任何帮助是极大的赞赏。

4

2 回答 2

2

我相信下面的多表 UPDATE 做同样的事情,而不使用子查询:

UPDATE cataloginventory_stock_item AS csi
 JOIN catalog_product_entity AS cpe ON csi.product_id = cpe.entity_id
 JOIN catalog_product_relation AS cpr ON cpr.parent_id = cpe.entity_id
 JOIN cataloginventory_stock_item AS cisi ON cisi.product_id = cpr.child_id
SET csi.is_in_stock = 1
WHERE cpe.type_id = 'configurable' AND csi.is_in_stock = 0 AND cisi.qty > 0;

我假设 cisi.qty 永远不会是负数。因此,如果找到任何 qty>0 的行,则 SUM(qty) 将大于零。

PS:您的原始查询使用 LEFT JOIN,就好像它是一个 INNER JOIN。您应该研究不同类型的连接是如何工作的

于 2013-09-27T18:09:35.273 回答
1

通过为您选择查询提供别名来尝试这个

UPDATE cataloginventory_stock_item
SET is_in_stock = 1
WHERE product_id IN (
SELECT   new_table.product_id  FROM (

 SELECT entity_id AS product_id FROM catalog_product_entity cpe
    LEFT JOIN cataloginventory_stock_item csi ON csi.product_id = cpe.entity_id
    WHERE cpe.type_id = 'configurable'
    AND csi.is_in_stock = 0
    AND (SELECT SUM(qty) FROM catalog_product_relation cpr LEFT JOIN cataloginventory_stock_item cisi ON cisi.product_id = cpr.child_id WHERE cpr.parent_id = cpe.entity_id) > 0
) new_table

)
于 2013-09-27T17:55:54.170 回答