I have a table lets call it table1, and the data in two of the columns has been destroyed.
Fortunately I have an old backup of the table.
In the old backup the values for the two columns in question are correct but the rest of the columns are outdated so I can't simply import the whole dump.
So instead I've imported it into another table which I'll call table2. Each record has an id which is the same in both tables.
So basically I need a query that will go through each record in table1 and update column1 and column2 with the corresponding values from table2.
The subquery either returns a single row, or else has no correlated column references. The subquery is in the UPDATE statement WHERE clause, using Condition with Subquery syntax. No SPL routine in the subquery can reference the same table that UPDATE is modifying.
Like SELECT , the UPDATE statement can have a subquery in several places or clauses. In an UPDATE , the two clauses in which subqueries are used most commonly are SET and WHERE . The SET clause is where we define the new value for the column being modified by the UPDATE .
Original table is table1 and backup table is table2
UPDATE table1 t1 JOIN table2 t2 ON t1.id = t2.id SET t1.col1 = t2.col1, t1.col2 = t2.col2, ...
This will work on all flavours of SQL database:
update table1 t set column1 = (select column1 from old_table where id = t.id), column2 = (select column2 from old_table where id = t.id);
There's no need for any special/aggregate functions, because the id match will hit exactly one row.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With