简体   繁体   中英

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

I have two tables and .
I'm doing some changes and I realized that is not needed, but this table has lots of data already and I need to pass the values of from to . ,但是此表已经有很多数据,我需要将的值从传递到

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 value from to when the on is equal to the on . 通过时就等于

For example, the row on where the is 1 would have the = 14. 为1的行的 = 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM