问题
I am reading in data from an XML file. Due to an error at the source it is one day out, so after loading into the database I use this SQL statement to increment the date.
UPDATE 2011_electricity SET DATE = DATE_ADD( DATE, INTERVAL 1 DAY )
Last week it worked fine, however now I get an error:
MySQL said:
#1062 - Duplicate entry '2011-07-20' for key 1
I have one primary key on the data field. This is how the database looks:
date energy daynum
2011-06-29 0.05 4197
2011-07-19 0.20 4219
2011-07-20 17.07 4220
2011-07-21 11.56 4221
2011-07-22 18.18 4222
2011-07-23 24.92 4223
2011-07-24 10.56 4224
2011-07-25 12.68 4225
2011-07-26 10.06 4226
2011-07-27 19.72 4227
2011-07-28 19.02 4228
2011-07-29 17.92 4229
2011-07-30 14.49 4230
2011-07-31 10.84 4231
2011-08-01 13.38 4232
2011-08-02 14.86 4233
I cannot see any duplicate there, so do not understand the error, is there a better way to carry out mysql code to increment the day by 1?
回答1:
This is a problem on how MySQL's UPDATE
works, row by row as p.cambell explained. Another way to bypass this issue, is to explicitely tell the engine how to order the updates (another MySQL quirk):
UPDATE 2011_electricity
SET DATE = DATE_ADD( DATE, INTERVAL 1 DAY )
ORDER BY DATE DESC
Rule of thumb: If you want to increase the PKs (or other Unique Key), order by descending. If you want to decrease the PKs, order by ascending.
回答2:
It sounds like you're trying to update the PK values on the table. Aside: suggest finding another PK for this table. Here's what's happening.
Row by row:
- update the PK for
2011-06-29
to be2011-06-30
. This succeeds as there's no other row with that PK value. - update the PK for
2011-07-19
to be2011-07-20
. This fails as there's already another row with that PK value. The pre-existing row's PK hasn't been incremented yet. We've now violated the PK constraint.
Suggest modifying your approach to either:
- Delete all your new data in the table, and reload from source as you're doing now.
- leverage a staging/temp table if deleting isn't an option. You might want to swap out rows selectively as per your needs.
来源:https://stackoverflow.com/questions/6968247/mysql-giving-duplicate-entry-error-when-trying-to-increment-date-field