0

I have inherited a table with a field "sku" with should be unique, but thanks to a failing sku-generating method is now littered with dozens of duplicates all around.

I need to quickly fix these duplicates (other parts of the application are failing when encountering these duplicate records) by running an update and appending the record ID to the SKU (which is a valid solution for the time being for this application).

I'm trying to run:

UPDATE
 main_product_table
SET sku = CONCAT(sku, '-', CAST(product_id as CHAR) )

WHERE sku IN (
  SELECT sku FROM main_product_table
  GROUP BY sku
  HAVING COUNT(*) > 1
);

But I receive:

You can't specify target table 'main_product_table' for update in FROM clause

Is there a way to accomplish the same? Is mysql complaining about me having main_product_table both in the update and in the subquery to get the duplicates?

Thanks!

2
  • 1
    I guess it is a problem with using the same table name twice. Try using unique aliases for the tables. Commented Jan 20, 2016 at 8:40
  • No, that's not it. Tried aliasing both tables, same result. (For the record, the error references the first alias, not the sencond) Commented Jan 20, 2016 at 8:43

1 Answer 1

2

Try this:

UPDATE
 main_product_table
SET sku = CONCAT(sku, '-', CAST(product_id as CHAR) )

WHERE sku IN (
select * from  ( SELECT sku FROM main_product_table
  GROUP BY sku
  HAVING COUNT(*) > 1) as p
);

Added table alias in inner query.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.