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:
To create a composite key, use the following syntax:
CREATE INDEX <index_name> ON <table_name> (<column1>, <column2>);
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);
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;
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!