What are practical differences between `REPLACE` and `INSERT … ON DUPLICATE KEY UPDATE` in MySQL?

前端 未结 8 1452
清酒与你
清酒与你 2020-11-28 06:59

What I need is to set the values of all the fields of a record with a particular key (the key is composite actually), inserting the record if there is no record with such a

8条回答
  •  独厮守ぢ
    2020-11-28 07:12

    REPLACE seems to be necessary sometimes because INSERT IGNORE doesn't seem to work with data transformations.

    If I do this, I only set largestCityPop to itself:

    INSERT IGNORE INTO largestCities (stateID, largestCityPop, statePop) SELECT stateID, MAX(city.pop) as largestCityPop, state.pop FROM city JOIN state on city.stateID = state.ID GROUP BY city.stateID ON DUPLICATE KEY UPDATE largestCityPop = largestCityPop

    If I do this, I am using the GROUP function improperly:

    INSERT IGNORE INTO largestCities (stateID, largestCityPop, statePop) SELECT stateID, MAX(city.pop) as largestCityPop, state.pop FROM city JOIN state on city.stateID = state.ID GROUP BY city.stateID ON DUPLICATE KEY UPDATE largestCityPop = MAX(city.pop)

    And if I do this, MySQL won't recognize the column name:

    INSERT IGNORE INTO largestCities (stateID, largestCityPop, statePop) SELECT stateID, MAX(city.pop) as largestCityPop, state.pop FROM city JOIN state on city.stateID = state.ID GROUP BY city.stateID ON DUPLICATE KEY UPDATE largestCityPop = city.largestCityPop

    This works, but seems just plain ugly:

    INSERT IGNORE INTO largestCities (stateID, largestCityPop, statePop) SELECT * FROM (SELECT stateID, MAX(city.pop) as biggestCityPop, state.pop FROM city JOIN state on city.stateID = state.ID GROUP BY city.stateID) x ON DUPLICATE KEY UPDATE largestCityPop = biggestCityPop

提交回复
热议问题