Miguel Santos
Miguel Santos

Reputation: 7

Update table new column with values from another table (MySQL)

I have two tables table1 and table2.
I'm doing some changes and I realized that table2 is not needed, but this table has lots of data already and I need to pass the values of ID_B from table2 to table1.

Here's the structure:

table1

 ID_table1 |  ID_table2 | ID_B      
  1        |   1        |    
  2        |   3        |    
  3        |   1        |    
  4        |   2        |    

table2

 ID_table2 |    ID_B  
  1        |     14  
  2        |     26  
  3        |     26  

So what I want is the MySQL query to pass the ID_B value from table2 to table1 when the ID_table2 on table1 is equal to the ID_table2 on table2.

For example, the row on table1 where the ID_table1 is 1 would have the ID_B = 14.

Can you help me on this? Thanks in advance,

Miguel.

Upvotes: 0

Views: 69

Answers (2)

Abhik Chakraborty
Abhik Chakraborty

Reputation: 44844

Using JOINs you can do as.

update table1 t1
inner join 
table2 t2 on t2.ID_table2 = t1.ID_table2
set t1.ID_B = t2.ID_B

DEMO

Upvotes: 1

Olli
Olli

Reputation: 1738

You could try it like so:

UPDATE
  table1 AS target,
  (SELECT ID_table2, ID_B FROM table2) AS source
SET
  target.ID_B = source.ID_B
WHERE
  target.ID_TABLE2 = source.ID_table2

Upvotes: 0

Related Questions