I want to do a query to update values that I forgot to copy over in a mass insert. However I’m not sure how to phrase it.
UPDATE table
SET text_field_1 = (SELECT text_field_2
FROM other_table
WHERE id = **current row in update statement, outside parens**.id )
How do I do this? It seems like a job for recursion.
Use:
Warning
If there’s no supporting record in
other_table,text_field_1will be set to NULL.Explanation
In standard SQL, you can’t have table aliases on the table defined for the UPDATE (or DELETE) statement, so you need to use full table name to indicate the source of the column.
It’s called a correlated subquery — the correlation is be cause of the evaluation against the table from the outer query.
Clarification
MySQL (and SQL Server) support table aliases in UPDATE and DELETE statement, in addition to JOIN syntax:
…is not identical to the provided query, because only the rows that match will be updated — those that don’t match, their
text_field_1values will remain untouched. This is equivalent to the provided query: