質問

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.

役に立ちましたか?

解決

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

他のヒント

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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top