Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql: Update table with select max of another table [duplicate]

Tags:

mysql

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?

like image 411
Simone Giusti Avatar asked Jan 20 '17 14:01

Simone Giusti


People also ask

How do I update two columns at a time in MySQL?

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.

How to update a mySQL table with values from another table?

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.

What is the MySQL update join syntax?

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.

How do I do a cross-table update in MySQL?

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.

What is another table linked to the table to update?

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.


1 Answers

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
);
like image 174
SlimsGhost Avatar answered Oct 23 '22 20:10

SlimsGhost