Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL update table based on another tables value

I have a two tables,

Here is my first table,

ID      SUBST_ID        CREATED_ID 1       031938          TEST123 2       930111          COOL123 3       000391          THIS109 4       039301          BRO1011 5       123456          COOL938 ...     ...             ... 

This is my second table,

ID      SERIAL_ID       BRANCH_ID 1       039301          NULL 2       000391          NULL 3       123456          NULL ...     ...             ... 

I need to some how update all rows within my second table using data from my first table.

It would need to do this all in one update query.

Both SUBST_ID and SERIAL_ID match, it needs to grab the created_id from the first table and insert it into the second table.

So the second table would become the following,

ID      SERIAL_ID       BRANCH_ID 1       039301          BRO1011 2       000391          THIS109 3       123456          COOL938 ...     ...             ... 

Thank you for your help and guidance.

like image 831
verheesj Avatar asked Sep 12 '12 18:09

verheesj


People also ask

How do you UPDATE a record based on another table in SQL?

UPDATE syntax:UPDATE table_name SET column_name = value WHERE condition; To perform the above function, we can set the column name to be equal to the data present in the other table, and in the condition of the WHERE clause, we can match the ID. we can use the following command to create a database called geeks.

How do you UPDATE a column based on another column in a table?

UPDATE table SET col = ( SELECT other_col FROM other_table WHERE other_table. table_id = table.id ); Perhaps an easier way is to specify multiple tables after the UPDATE clause. Only the SET expression will perform updates but listing additional tables will allow the tables to be included.


2 Answers

UPDATE TABLE2        JOIN TABLE1        ON TABLE2.SERIAL_ID = TABLE1.SUBST_ID SET    TABLE2.BRANCH_ID = TABLE1.CREATED_ID; 
like image 152
Tom Avatar answered Sep 20 '22 19:09

Tom


In addition to Tom's answer if you need to repeat the operation frequently and want to save time you can do:

UPDATE TABLE1        JOIN TABLE2        ON TABLE1.SUBST_ID = TABLE2.SERIAL_ID SET    TABLE2.BRANCH_ID = TABLE1.CREATED_ID WHERE TABLE2.BRANCH_ID IS NULL 
like image 32
RafaSashi Avatar answered Sep 21 '22 19:09

RafaSashi