Home > Database > Mysql Tutorial > How to Update MySQL Table Data Based on Another Table's Values?

How to Update MySQL Table Data Based on Another Table's Values?

Barbara Streisand
Release: 2025-01-17 04:47:09
Original
816 people have browsed it

How to Update MySQL Table Data Based on Another Table's Values?

Update MySQL table data based on values ​​from another table

Suppose you have two tables with similar structure, tableA and tableB:

id name value
1 Joe 22
2 Derk 30

The task is to copy the value of the value column of tableA to the value column of tableB based on the matching name values ​​in the two tables.

To do this, you can use the following MySQL UPDATE statement:

<code class="language-sql">UPDATE tableB
INNER JOIN tableA ON tableB.name = tableA.name
SET tableB.value = tableA.value;</code>
Copy after login

This statement performs an INNER JOIN operation between tableA and tableB based on the name column, and updates the value column in tableB with the corresponding value in tableA.

Condition-based dynamic value update:

If you need to dynamically update the value column in tableB based on the value in tableA, you can use the following method:

<code class="language-sql">UPDATE tableB
INNER JOIN tableA ON tableB.name = tableA.name
SET tableB.value = IF(tableA.value > 0, tableA.value, tableB.value)
WHERE tableA.name = 'Joe';</code>
Copy after login

Here, the IF() function checks whether tableA.value is greater than 0. If true, set tableB.value to the value of tableA.value; otherwise, retain the original value in tableB.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template