I have 2 different database in my MySql server.
First table DB1.contacts:
id | name | code
1 | foo | 157
2 | foo | 95
3 | foo | 210
Second table DB2.paperworks:
id | name | contact_id
1 | foo | 0
I would like to update DB2.paperworks, set DB2.paperworks.contact_id = max(DB1.contacts.code) of DB1.contacts.contacts table where DB2.paperworks.name = DB1.contacts.name
My desidered output should be:
Second table after query DB2.paperworks:
id | name | contact_id
1 | foo | 210
This is my query:
UPDATE DB2.paperworks
JOIN DB1.contacts
ON DB2.paperworks.name = DB1.contacts.name
SET DB2.paperworks.contact_id = DB1.contacts.code
I don't understand how to write che "MAX(code)" condition. Can you help me, please?
MySQL UPDATE command can be used to update multiple columns by specifying a comma separated list of column_name = new_value. Where column_name is the name of the column to be updated and new_value is the new value with which the column will be updated.
Updating a MySQL table with values from another table? Updating a MySQL table with values from another table? We can update another table with the help of inner join. Let us create two tables. Look at the above output, the last name is matching from the first table record. Now, I will write the query for UPDATE − Look at the sample output.
Let’s examine the MySQL UPDATE JOIN syntax in greater detail: First, specify the main table ( T1 ) and the table that you want the main table to join to ( T2 ) after the UPDATE clause. Notice that you must specify at least one table after the UPDATE clause. The data in the table that is not specified after the UPDATE clause will not be updated.
In MySQL, you can use the JOIN clauses in the UPDATE statement to perform the cross-table update. The syntax of the MySQL UPDATE JOIN is as follows: UPDATE T1, T2, [ INNER JOIN | LEFT JOIN ] T1 ON T1.C1 = T2.
This another table might be linked to the table to be updated based on one or more columns. For example, consider we have two tables. One is student_details and other is student_ids. Both of these tables have a common column named stu_firstName.
A slightly simpler form of update
will do the trick:
UPDATE DB2.paperworks
SET DB2.paperworks.contact_id = (
select max(DB1.contacts.code)
from DB1.contacts
where DB1.contacts.name = DB2.paperworks.name
group by DB1.contacts.code
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With