Home >Database >Mysql Tutorial >How to Update SQL Table Rows Based on Matching Usernames?

How to Update SQL Table Rows Based on Matching Usernames?

DDD
DDDOriginal
2025-01-15 08:48:17392browse

How to Update SQL Table Rows Based on Matching Usernames?

Update the row value in the table based on the matching username

Q: Update table value

In SQL Database, you have two tables, table_a and table_b, both of which have a common column called user_name. You want to copy specific columns (named column_b_1 and column_b_2) in table_b to corresponding columns (column_a_1 and column_a_2) in table_a based on matching user_name values. How can I achieve this using SQL statements?

Answer: Solution

If the appropriate indexes are in place, you can use the following UPDATE statement:

<code class="language-sql">UPDATE table_a
SET
  column_a_1 = (SELECT table_b.column_b_1 
                    FROM table_b
                    WHERE table_b.user_name = table_a.user_name),
  column_a_2 = (SELECT table_b.column_b_2
                    FROM table_b
                    WHERE table_b.user_name = table_a.user_name)
WHERE
  EXISTS (
    SELECT *
    FROM table_b
    WHERE table_b.user_name = table_a.user_name
  );</code>

Note: This UPDATE statement uses a subquery to retrieve the column values ​​from table_b that correspond to each row in table_a that has a matching user_name.

If performance is a concern, consider using SELECT and JOIN operations to build a temporary table to store the modified rows. You can then delete the existing data from table_a and repopulate it from the temporary table.

The above is the detailed content of How to Update SQL Table Rows Based on Matching Usernames?. 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