Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Update table by mapping two columns to each other

I have the following two tables:

        Table A
+-------------------+
|___User___|__Value_|
|    3     |  a     |
|    4     |  b     |
|    5     |  c     |
|____6_____|__d_____|



        Table B
+-------------------+
|___User___|__Value_|
|    1     |        |
|    4     |        |
|    5     |        |
|____9_____|________|

My job is to take user from Table A (and their correspondings value) and then map it to Table B and insert those values in there. So from the above example Table B should look like this after running the script:

        Table B
+-------------------+
|___User___|__Value_|
|    1     |        |
|    4     |  b     |
|    5     |  c     |
|____9_____|________|

My question is how can I construct an SQL query that will do this for me in an efficient way, if Table A contains 300,000 + entries and Table B contains 70,000 entries?

NOTES: In Table A the User field is not unique and neither is the Value field. However in Table B, both the User and Value fields are unique and should not appear more than once. Neither are primary keys for either tables.

like image 306
Allen S Avatar asked Jan 25 '16 12:01

Allen S


People also ask

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

In such a case, you can use the following UPDATE statement syntax to update column from one table, based on value of another table. UPDATE first_table, second_table SET first_table. column1 = second_table. column2 WHERE first_table.id = second_table.

How do I make two columns in one UPDATE in SQL?

To update multiple columns use the SET clause to specify additional columns. Just like with the single columns you specify a column and its new value, then another set of column and values. In this case each column is separated with a column.

How do I UPDATE two columns in a table?

We can update multiple columns by specifying multiple columns after the SET command in the UPDATE statement. The UPDATE statement is always followed by the SET command, it specifies the column where the update is required.


2 Answers

Could be this

update table_b as b 
inner join table_a as a on a.User = b.User
set b.value = a.value 
like image 140
ScaisEdge Avatar answered Sep 25 '22 06:09

ScaisEdge


In real-world situations, it would be more likely that you want a predictable value, such as the greatest value for any given user. In that case you would want

update table_b as b
inner join (
   select user, max(value) from table_a
   group by user ) as a_max on a.user = b.user
set b.value = a_max.value
like image 22
Alan Hadsell Avatar answered Sep 24 '22 06:09

Alan Hadsell