I need to be able to swap values that are used in a primary key. Meaning, in one update statement, I need to change id 1 to id 2, and id 2 to id 1.
In other relational databases, (Sql Server and Oracle), it seems that the transaction that does the update applies the Primary key contraint after checking the values if update succeeded. This seems to be in line with what a transaction should do before it commits the change. In mySql, I get a duplicate entry error code.
Am I missing something? Is there a way around this? I'm using ver 5.1.60, InnoDB
CREATE TABLE testUpdateKeys (
optId INT PRIMARY KEY
,_rowId INT
);
INSERT INTO testUpdateKeys SELECT 1,1;
INSERT INTO testUpdateKeys SELECT 2,2;
INSERT INTO testUpdateKeys SELECT 3,3;
SELECT * FROM testUpdateKeys;
-- this should fail
UPDATE testUpdateKeys
SET optId = 2
WHERE _rowId = 1;
CREATE TABLE testUpdateKeys_oper ( _oper CHAR(1), _rowId INT, optId INT);
INSERT INTO testUpdateKeys_oper SELECT 'U', 2, 1;
INSERT INTO testUpdateKeys_oper SELECT 'U', 1, 2;
SELECT * FROM testUpdateKeys_oper;
-- This works in SQL Server and Oracle
UPDATE testUpdateKeys a, testUpdateKeys_oper b
SET a.optId = b.optId
WHERE
a._rowid = b._rowId
AND b._oper = 'U';
SELECT * FROM testUpdateKeys;
DROP TABLE testUpdateKeys;
DROP TABLE testUpdateKeys_oper;
UPDATE. Not only is it going to crash your data integrity, InnoDB will try to physically reorder records resulting in slower inserting performance. – N.B. Jan 27 '12 at 16:51