Johnny
Johnny

Reputation: 141

MySQL Import only one column to existing table

I have the following problem.

I have a table which contains the following fields (example):

id, id2, id3, id4

Due to a mistake, I have accidently deleted all values of id3. (They are NULL now).

I have a second file (backup) which is a bit older, so it doesn't have the same count as the damaged table. The id3 is present there.

How do I "join" these tables, to restore at least the bigger part? Insert id3 ONLY to the damaged table from the non-damaged table?

I tried this:

UPDATE table1 SET `id3` = SELECT `id3` FROM table2

In my case, only phpMyAdmin or SQL Syntax solution (no console) would work...

Please help!

Upvotes: 0

Views: 2923

Answers (2)

Niket Malik
Niket Malik

Reputation: 1105

Assuming id is an unique attribute.

You can simply run this query:

UPDATE table1 SET id3 = (SELECT id3 FROM table2 WHERE table2.id = table1.id)

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1269973

If we assume that one, two, or three of the ids define each row, then you can use join:

update table1 t1 join
       table2 t2
       on t1.id = t2.id
    set t1.id3 = t2.id3;

This assumes that id is unique in the two tables. You might want to use a more complex expression:

update table1 t1 join
       table2 t2
       on t1.id = t2.id and t1.id2 = t2.id2 and t1.id4 = t2.id4
    set t1.id3 = t2.id3;

Upvotes: 1

Related Questions