Home >Database >Mysql Tutorial >How to Use Composite Keys with MySQL's `UPDATE ON DUPLICATE KEY`?
Composite Key for MySQL's 'UPDATE ON DUPLICATE KEY'
Question:
How can you efficiently perform a query that updates a row if a specific combination of values already exists (using 'UPDATE ON DUPLICATE KEY'), but only if a unique key is defined?
Answer:
MySQL allows the creation of composite keys, which consist of multiple columns. By defining a composite key, you can utilize the 'UPDATE ON DUPLICATE KEY' syntax even when the unique constraint involves a combination of values.
Implementation:
Create a Composite Index:
Use the following syntax to create an index on multiple columns:
CREATE INDEX index_name ON table_name (column1, column2);
Insert or Update:
Once the composite index is created, you can use the following query to insert a new row or update an existing one based on the composite key:
INSERT INTO table_name (column1, column2) VALUES (value1, value2) ON DUPLICATE KEY UPDATE column3 = column3 + 1;
In this example, the 'column1' and 'column2' values act as the composite key. If a row with the same 'column1' and 'column2' values already exists, the 'column3' value will be incremented by one. Otherwise, a new row will be inserted.
The above is the detailed content of How to Use Composite Keys with MySQL's `UPDATE ON DUPLICATE KEY`?. For more information, please follow other related articles on the PHP Chinese website!