Home > Database > Mysql Tutorial > How to Insert or Update MySQL Rows Based on a Unique Key?

How to Insert or Update MySQL Rows Based on a Unique Key?

Susan Sarandon
Release: 2024-12-26 21:47:15
Original
277 people have browsed it

How to Insert or Update MySQL Rows Based on a Unique Key?

Inserting or Updating MySQL Rows Based on Unique Key

Consider the scenario where you aim to add data to a table but face the challenge of inserting new rows while updating existing ones based on the uniqueness of a specific column (datenum).

To address this requirement, you may initially attempt to utilize an UPDATE statement as exemplified in the question; however, this approach is limited to modifying existing rows only. For scenarios where the datenum value doesn't exist in the table, no action will be taken.

To accomplish both insertion and updation based on the datenum unique column, MySQL provides the INSERT ... ON DUPLICATE KEY UPDATE syntax. This syntax enables you to define an insert operation that automatically updates the row if a duplicate key is encountered.

Here's an improved version of the UPDATE statement using the INSERT ... ON DUPLICATE KEY UPDATE syntax:

INSERT INTO AggregatedData (datenum,Timestamp)
VALUES ("734152.979166667","2010-01-14 23:30:00.000")
ON DUPLICATE KEY UPDATE 
  Timestamp=VALUES(Timestamp)
Copy after login

In this statement, the unique key column datenum is used in the INSERT clause, while the updated value for Timestamp is specified in the ON DUPLICATE KEY UPDATE clause. This ensures that if a row with the same datenum already exists, the Timestamp column will be updated with the provided value, while other columns remain unchanged.

By employing this technique, you achieve both insertion of new rows and updation of existing rows in your MySQL table based on the unique key column.

The above is the detailed content of How to Insert or Update MySQL Rows Based on a Unique Key?. 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