MySQL 'UPDATE ON DUPLICATE KEY' without a unique column?

后端 未结 3 1455
逝去的感伤
逝去的感伤 2021-01-12 10:31

What are peoples\' thoughts on the most performance efficient way to do the following query:

  • 3 column table

  • if the combination of col_

相关标签:
3条回答
  • 2021-01-12 10:54

    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;
    
    0 讨论(0)
  • 2021-01-12 10:55

    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

    0 讨论(0)
  • 2021-01-12 11:14

    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.

    0 讨论(0)
提交回复
热议问题