Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL update with sub select

Tags:

mysql

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.

like image 282
geoffs3310 Avatar asked Jun 24 '11 10:06

geoffs3310


People also ask

Can we use subquery in UPDATE statement in MySQL?

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.

Can UPDATE be used in a subquery?

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 .


2 Answers

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, ... 
like image 174
niktrs Avatar answered Sep 25 '22 06:09

niktrs


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.

like image 40
Bohemian Avatar answered Sep 24 '22 06:09

Bohemian