Nick Rolando
Nick Rolando

Reputation: 26177

Update table using JOIN and subquery

I'm trying to run an UPDATE that JOINs to other tables, and has a subquery in the WHERE clause. However, I'm getting this error:

1093 - You can't specify target table 'csi' for update in FROM clause

Here's my query:

UPDATE mage_cataloginventory_stock_item csi
INNER JOIN mage_catalog_product_entity cpe
ON csi.product_id = cpe.entity_id
SET csi.Is_in_Stock = 0
WHERE cpe.sku IN (
    SELECT cpe.sku
    FROM mage_catalog_product_entity cpe 
    INNER JOIN mage_cataloginventory_stock_item CSI
    ON CSI.product_id = cpe.entity_id
    INNER JOIN mage_cataloginventory_stock_status CISS
    ON CSI.product_id = CISS.product_ID
    INNER JOIN mage_catalog_product_entity_int cpei
    ON cpe.entity_id = cpei.entity_id
    WHERE type_id = 'simple'
    AND cpei.attribute_id = 80
    AND CSI.Qty = 0 AND cpei.value = 1
)

I see from other sources you can't specify the table being updated in a subquery, but I have no idea how else to do it.. Hoping someone can help point me in the right direction to get this working as I need. Thanks!

Upvotes: 0

Views: 258

Answers (1)

Bernhard Barker
Bernhard Barker

Reputation: 55619

You could just replace cpe and CSI in the sub-query with cpe2 and CSI2 or whichever names you choose.

The above would not take the current rows of the tables your updating into account at all.

It could be that this is not what you want. In that case, try:

UPDATE mage_cataloginventory_stock_item csi
INNER JOIN mage_catalog_product_entity cpe
ON csi.product_id = cpe.entity_id
SET csi.Is_in_Stock = 0
WHERE cpe.sku IN (
    SELECT cpe.sku
    /* removed joins */
    FROM mage_cataloginventory_stock_status CISS
    INNER JOIN mage_catalog_product_entity_int cpei
    ON cpe.entity_id = cpei.entity_id
    WHERE type_id = 'simple'
    AND cpei.attribute_id = 80
    AND cpei.value = 1
    /* moved join condition here */
    AND cpe.product_id = CISS.product_ID
    AND CSI.Qty = 0
)

Depending on a few things, the below could do the same: (e.g. cpe.sku must be unique, otherwise you may be able to get it to work with another join)

UPDATE mage_cataloginventory_stock_item csi
INNER JOIN mage_catalog_product_entity cpe
  ON csi.product_id = cpe.entity_id
INNER JOIN mage_cataloginventory_stock_status CISS
  ON cpe.product_id = CISS.product_ID
INNER JOIN mage_catalog_product_entity_int cpei
  ON cpe.entity_id = cpei.entity_id
SET csi.Is_in_Stock = 0
WHERE type_id = 'simple'
  AND cpei.attribute_id = 80
  AND cpei.value = 1
  AND CSI.Qty = 0

Upvotes: 1

Related Questions