Home > Database > Mysql Tutorial > How to Update Specific Columns in MySQL While Preserving Others?

How to Update Specific Columns in MySQL While Preserving Others?

DDD
Release: 2024-11-05 19:31:02
Original
607 people have browsed it

How to Update Specific Columns in MySQL While Preserving Others?

Updating Columns in MySQL

In a situation where you possess a table with multiple columns containing data, you may encounter the need to modify specific columns while preserving the values in others. For instance, consider a scenario with a MySQL table named "table1" comprising three columns: "key_col," "col_a," and "col_b."

Query Premise:

Your goal is to update the values within the "col_a" column, leaving "col_b" intact. The intended outcome is represented by the following query:

INSERT INTO table1 AS t1 (key_col, col_a) VALUES ("k1", "foo"), ("k2", "bar");
Copy after login

Query Issue:

However, upon executing this query, MySQL will likely confront you with an error. The reason for this unsuccessful attempt lies in the utilization of the "INSERT" statement, which is primarily designed for inserting new rows into a table. To achieve the desired result of updating specific table cells, it is imperative to employ the "UPDATE" statement instead.

Solution using UPDATE:

The "UPDATE" syntax follows a precise format:

UPDATE table_name SET column_name = new_value WHERE condition;
Copy after login

Example:

In your case, the suitable queries for updating "col_a" are as follows:

UPDATE table1 SET col_a='k1', col_b='foo' WHERE key_col='1';
UPDATE table1 SET col_a='k2', col_b='bar' WHERE key_col='2';
Copy after login

By executing these queries, you can effectively modify the values in "col_a" while preserving the contents of "col_b" for rows designated by the specified "key_col" values.

The above is the detailed content of How to Update Specific Columns in MySQL While Preserving Others?. 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