Question

I'm having a problem with MySQL

I have two tables, I want to store Val1 from Table 2 into Val2 in Table 1

Table1

ID-----Val1-----Val2
1------A--------NULL
2------B--------NULL
3------C--------NULL
4------D--------NULL
5------E--------NULL

Table2

ID-----Val1
1------aaa
2------bbb
3------ccc
4------ddd
5------eee

So that Table1 now looks like

Table1

ID-----Val1-----Val2
1------A--------aaa
2------B--------bbb
3------C--------ccc
4------D--------ddd
5------E--------eee

Right now, I have

INSERT INTO Table1(Val2) SELECT Val1 FROM Table2 WHERE Table1.ID=Table2.ID;

Any help is appreciated!

Was it helpful?

Solution

You can use either a subquery (SQLize):

UPDATE Table1
SET Val2 = ( SELECT Val1 FROM Table2 WHERE Table1.ID = Table2.ID )
WHERE Val2 IS NULL

or a multi-table update (SQLize):

UPDATE Table1, Table2
SET Table1.Val2 = Table2.Val1
WHERE Table1.ID = Table2.ID AND Table1.Val2 IS NULL

or the same with an explicit JOIN (SQLize):

UPDATE Table1 JOIN Table2 ON Table1.ID = Table2.ID
SET Table1.Val2 = Table2.Val1
WHERE Table1.Val2 IS NULL

(I assume you only want to update the rows in Table1 for which Val2 is NULL. If you'd rather overwrite the values for all rows with matching IDs in Table2, just remove the WHERE Table1.Val2 IS NULL condition.)

OTHER TIPS

update table1 
inner join table2 on table1.id = table2.id
set table1.val2 = table2.val1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top