Home >Database >Mysql Tutorial >How Can I Use INSERT...ON DUPLICATE KEY UPDATE with a Composite Key in MySQL?
In MySQL, you can combine multiple columns to create a unique key, known as a composite key. This enables the use of the ON DUPLICATE KEY clause even when the table lacks a single unique column.
To update a column if a row with a specific combination of values in col_1 and col_2 already exists, or insert a new row if it doesn't, use the following query structure:
INSERT INTO my_table (col_1, col_2, col_3) VALUES ('value1', 'value2', 'value3') ON DUPLICATE KEY UPDATE col_3=col_3+1;
To create a composite key over col_1 and col_2, run the following command:
CREATE UNIQUE INDEX my_composite_index ON my_table (col_1, col_2);
Using a composite key for ON DUPLICATE KEY offers several advantages:
The above is the detailed content of How Can I Use INSERT...ON DUPLICATE KEY UPDATE with a Composite Key in MySQL?. For more information, please follow other related articles on the PHP Chinese website!