I have a list of items. Original items were set a property, but there was a bug in the app where child rows didn’t inherit the property.
Here is what I’ve tried to fix it:
UPDATE queue_items SET property_value = (
SELECT property_value FROM queue_items WHERE id = origin_id
) WHERE property_value IS NULL OR LENGTH(property_value) < 5 AND origin_id IS NOT NULL;
But I get: [HY000][1093] You can’t specify target table ‘queue_items’ for update in FROM clause
2
Answers
The query should be similar to:
fiddle
If the condition is more complex than simple "replace NULL with parent value" then use according CASE expression instead of COALESCE().
Main issue "You can’t specify target table…"
This is a ridiculous problem specific to MySQL. You cannot reference the updated table in a subquery directly, so
must be changed to something like
Be aware though, that there are other issues in your update statement.
Secondary issue #1:
How many rows do you think you’ll get with this? You don’t specify the columns’ tables, so the local table is taken, which is
What you really want to do is to have one of the columns be taken from the updated row. Use table aliases to differentiate between updated row and parent row.
Secondary issue #2:
AND
has precedence overOR
. So what you have iswhile you probably want
Final statement: