Home > Database > Mysql Tutorial > How Can Composite Keys Improve MySQL's `UPDATE ON DUPLICATE KEY` Performance?

How Can Composite Keys Improve MySQL's `UPDATE ON DUPLICATE KEY` Performance?

Susan Sarandon
Release: 2024-12-03 10:21:13
Original
324 people have browsed it

How Can Composite Keys Improve MySQL's `UPDATE ON DUPLICATE KEY` Performance?

Composite Keys for Efficient MySQL 'UPDATE ON DUPLICATE KEY' Queries

When working with multi-column unique identifiers in MySQL, the challenge arises of efficiently handling both updates and insertions. While the 'UPDATE ON DUPLICATE KEY' syntax seems like a suitable solution, it requires a unique key to work.

However, you can create a composite key from multiple columns, which will allow 'UPDATE ON DUPLICATE KEY' to function as desired. Here's how to approach this:

Creating a Composite Key

To create a composite key, use the following syntax:

CREATE INDEX <index_name> ON <table_name> (<column1>, <column2>);
Copy after login

For example, let's create a composite key for the three-column table mentioned in the question:

CREATE INDEX unique_index ON my_table (col_1, col_2);
Copy after login

Using 'UPDATE ON DUPLICATE KEY'

Once the composite key is created, you can execute 'UPDATE ON DUPLICATE KEY' queries to either update or insert records based on the key values. The syntax is as follows:

INSERT INTO <table_name> (col_1, col_2, col_3) VALUES ('value1', 'value2', 'value3') ON DUPLICATE KEY UPDATE col_3=col_3+1;
Copy after login

In this query, if a record with the specified values of col_1 and col_2 already exists, col_3 will be incremented by 1. Otherwise, a new record will be inserted.

The above is the detailed content of How Can Composite Keys Improve MySQL's `UPDATE ON DUPLICATE KEY` Performance?. 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