Home > Database > Mysql Tutorial > How to Update a MySQL Column's Value Based on Data from Another Table?

How to Update a MySQL Column's Value Based on Data from Another Table?

DDD
Release: 2025-01-17 05:01:10
Original
426 people have browsed it

How to Update a MySQL Column's Value Based on Data from Another Table?

MySQL: Update column value based on data from another table

Question:

Suppose there are two tables with similar structures:

id name value
1 Joe 22
2 Derk 30

The task is to update the "value" column in table B with the value in table A based on the matching "name" value.

Solution:

You can use the SQL UPDATE statement with a JOIN clause to perform this update operation. Here is a possible query:

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

This query will update the "value" column of all rows in table B that match table A, based on the "name" column.

Dynamic value update:

You can modify the query to dynamically update table B.value based on the values ​​in table A.value. For example, the following query only updates table B.value if table A.value is greater than 0:

<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

In this example, the "value" column in the row with "name" "Joe" in Table B will be updated with the value from Table A only if the value in Table A is greater than 0. Otherwise, the existing values ​​in Table B will remain unchanged.

The above is the detailed content of How to Update a MySQL Column's Value Based on Data from Another Table?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template