MySQL 'UPDATE ON DUPLICATE KEY' without a unique column?
What are peoples' thoughts on the most performance efficient way to do the following query:
3 column table
if the combination of
col_1
andcol_2
values alr开发者_运维百科eady existUPDATE col_3
else
INSERT
new row
I assume i need some kind if UPDATE ON DUPLICATE KEY (which i've never used before), however I do not have a 'KEY' but instead a pair of two values (columns) to make a key...
You can create a PRIMARY
or UNIQUE
key out of multiple columns (called a composite key) in MySQL, which'll allow ON DUPLICATE KEY
to work just fine.
// create a composite index
CREATE INDEX my_composite_index ON my_table (column1, column2);
// insert or update
INSERT INTO my_table (column1, column2) VALUES ('value1', 'value2') ON DUPLICATE KEY UPDATE column3=column3+1;
Most efficient way is to create UNIQUE KEY and use ON DUPLICATE KEY UPDATE.
Slower way is to:
LOCK TABLE
SELECT TABLE (you need an index anyway for the best performance)
if exists, UPDATE
else INSERT
UNLOCK TABLES
Edit: Ignore my suggestions
You can use a composite key as ceejayoz said, however I think you need REPLACE INTO instead of UPDATE ON DUPLICATE KEY because REPLACE also inserts if no duplicate is found.
Note: I don't know the workings of UPDATE ON DUPLICATE KEY but it sounds like it doesn't perform inserts.
精彩评论