I have two tables, and want to update fields in T1 for all rows in a LEFT JOIN.
For an easy example, update all rows of the following result-set:
SELECT T1.* FROM T1 LEFT JOIN T2 ON T1.id = T2.id WHERE T2.id IS NULL
The MySQL manual states that:
Multiple-table UPDATE statements can use any type of join allowed in SELECT statements, such as LEFT JOIN.
But I cannot find the proper syntax for doing that in the documented multiple-tables UPDATE.
What is the proper syntax?
Note that for a
SELECT
it would be more efficient to useNOT IN
/NOT EXISTS
syntax:See the article in my blog for performance details:
LEFT JOIN
compared toNOT IN
Unfortunately,
MySQL
does not allow using the target table in a subquery in anUPDATE
statement, that's why you'll need to stick to less efficientLEFT JOIN
syntax.I will update field text in table A with
and come to this result:
where only one field from Table B is accepted, but I will come to this result:
The same can be applied to a scenario where the data has been normalized, but now you want a table to have values found in a third table. The following will allow you to update a table with information from a third table that is liked by a second table.
This would be useful in a case where you had users and groups, and you wanted a user to be able to add their own variation of the group name, so originally you would want to import the existing group names into the field where the user is going to be able to modify it.