I have a composite PK, where I need to update one of its PK value. But due to some internal issues, I can't fire update queries to a PK column.
So I'm firing DELETE and INSERT query.
This DELETE and INSERT is done inside a TRANSACTION (READ COMMITTED).
But sometimes, when two requests do update to the same row. On Duplicate entry for key PRIMARY errors are thrown. This occurs randomly, I tried a lot in reproducing this issue locally but I couldn't find the root cause.
Note: Due to some internal restrictions, I couldn't try the following things.
- Update query to PK
- Replace query
- Insert on duplicate or Insert Ignore queries
- Adding a running ID currently for this table will be a huge migration.
Kindly help me with this issue.
Update:
Sample Table Structure:
Table: temp
Create Table: CREATE TABLE `temp` (
`id1` int(11) NOT NULL,
`id2` int(11) NOT NULL,
`id3` int(11) NOT NULL,
`value` int(11) DEFAULT NULL,
PRIMARY KEY (`id1`,`id2`,`id3`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
Sample Data:
+-----+-----+-----+-------+
| id1 | id2 | id3 | value |
+-----+-----+-----+-------+
| 1 | 100 | 111 | 123 |
| 2 | 200 | 222 | 456 |
+-----+-----+-----+-------+
Sample Queries:
Transaction T1 tries to update ID1=3 value where id2=100
Delete from temp where id2=100
Insert into temp values(3,100,111,123);
Transaction T2 tries to update ID1=3 value where id2=100
Delete from temp where id2=100
Insert into temp values(3,100,111,123);
number of deletion and insertion will always be the same