1

I am currently using this query

insert into races(race_city_id, race_date, racers, division, elimination)
values (:race_city_id, :race_date, :racers, :division, :elimination)
on duplicate key update
    race_city_id = values(race_city_id),
    race_date = values(race_date),
    racers = values(racers),
    division = values(division),
    elimination = values(elimination);

with a unique key on race_date, division, and elimination. I am currently using on duplicate key, but on a duplicate key found, I need to either delete and insert a new row into races (2 queries) or somehow regenerate the id field of the row and update some fields in it. I am using InnoDB and I have read that when you update a row the primary key would be regenerated, but mine is not. The id is set to auto increment, so I'm not sure if there is a way to regenerate the key.

The query updates the row properly, but I just need the key to be regenerated too.

4
  • You realize you're attaching the values on the insert with pdo, but not on the duplicate keys? on duplicate key update race_city_id = values(:race_city_id), etc... Commented Sep 6, 2016 at 1:21
  • @Xorifelse I'm pretty sure that using value(xxx) takes the value that would be inserted, and in this case it was from pdo. This is what I have used for 4 other queries that I have made. dev.mysql.com/doc/refman/5.7/en/… Commented Sep 6, 2016 at 1:24
  • After doing a little research it seems you are correct, however the query does what it reads, it updates the values and leaves the id alone. Perhaps using replace into races would resolve your situation (obviously removing the on duplicate key update part) Commented Sep 6, 2016 at 1:35
  • @Xorifelse Well is there a way to make it regenerate the id? I guess I could find the max of every id, but then the auto increment feature would be off after that, right? Commented Sep 6, 2016 at 1:38

1 Answer 1

1

Change the query to:

replace into races(
  race_city_id, 
  race_date, 
  racers, 
  division, 
  elimination
) values (
  :race_city_id,
  :race_date,
  :racers,
  :division,
  :elimination
)

As replace into works exactly like insert except that if an old row in the table has the same value as a new row for a primary key or a unique index, the old row is deleted before the new row is inserted, generating a new id.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.