Home > Database > Mysql Tutorial > How Can I Efficiently Insert or Update Data Based on Two Conditions in SQL?

How Can I Efficiently Insert or Update Data Based on Two Conditions in SQL?

Barbara Streisand
Release: 2025-01-04 12:06:35
Original
609 people have browsed it

How Can I Efficiently Insert or Update Data Based on Two Conditions in SQL?

Insert or Update with Two Conditions

This problem appears straightforward; however, it necessitates finding an efficient time-wise solution. Consider a table with the following schema:

ID INTEGER PRIMARY KEY AUTOINCREMENT
name INTEGER
values1 INTEGER
values2 INTEGER
dates DATE
Copy after login

Each day, data is added to this table, resulting in new rows with future dates. The data in the 'name' column is drawn from a finite set. The desired behavior is to insert a new row if new data is available and update the existing row if a row with matching 'name' and 'dates' already exists.

Solution:

The appropriate method for this situation is the "INSERT INTO ... ON DUPLICATE KEY UPDATE" statement. This statement allows you to both insert new rows and update existing rows meeting specific conditions. In your case, the conditions are matching 'name' and 'dates'.

To use this method, your table must have a unique key (which can be a composite key) to detect the collision during insertion. This unique key can be the primary key or a composite key like this:

UNIQUE KEY(name, dates)
Copy after login

If a row with the same 'name' and 'date' already exists, the insert operation is detected as a conflict, and the update action specified in the "ON DUPLICATE KEY UPDATE" clause is performed.

Complete Example:

CREATE TABLE myThing (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name INT NOT NULL,
    values1 INT NOT NULL,
    values2 INT NOT NULL,
    dates DATE NOT NULL,
    UNIQUE KEY(name, dates)  -- This line is crucial
);

-- Insert a new row or update if a row with the same 'name' and 'date' exists
INSERT INTO myThing(name, values1, values2, dates) VALUES (777, 1, 1, '2015-07-11') ON DUPLICATE KEY UPDATE values2=values2+1;
Copy after login

By utilizing the "INSERT INTO ... ON DUPLICATE KEY UPDATE" statement, you can efficiently insert new rows or update existing rows based on the uniqueness of the specified key.

The above is the detailed content of How Can I Efficiently Insert or Update Data Based on Two Conditions in SQL?. 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