Home >Database >Mysql Tutorial >How to Update a MySQL Table Using Data from Another Table?

How to Update a MySQL Table Using Data from Another Table?

Susan Sarandon
Susan SarandonOriginal
2024-12-17 02:01:25507browse

How to Update a MySQL Table Using Data from Another Table?

Updating MySQL Table Based on Values from Another Table

Objective:
The task is to update values in one MySQL table (Table2) using data from another table (Table1) based on matching values between specific columns.

Tables:

  • Table1: Contains columns 'SUBST_ID', 'CREATED_ID'
  • Table2: Contains columns 'ID', 'SERIAL_ID', 'BRANCH_ID'

Matching Criteria:

  • Table1's 'SUBST_ID' column matches Table2's 'SERIAL_ID' column

Update Query:

To achieve the required update, use the following SQL query:

UPDATE Table2
JOIN Table1
ON Table2.SERIAL_ID = Table1.SUBST_ID
SET Table2.BRANCH_ID = Table1.CREATED_ID;

Explanation:

  • The JOIN clause merges rows from Table1 and Table2 based on the matching condition.
  • The SET clause updates the 'BRANCH_ID' column in Table2 with the 'CREATED_ID' from Table1 for matching rows.

Result:

After executing this query, Table2 will be updated with the 'BRANCH_ID' values retrieved from Table1 based on the matching 'SERIAL_ID' values. The resulting Table2 will be as follows:

  • ID: Same as the original Table2
  • SERIAL_ID: Same as the original Table2
  • BRANCH_ID: Values from Table1's 'CREATED_ID' column for matching rows

The above is the detailed content of How to Update a MySQL Table Using Data from Another Table?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn