I have a MySQL table. I must be able to add unique INT values for speed which is not an AUTO_INCREMENT column.
CREATE TABLE ki
(
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT
, comp_id INT(10) UNSIGNED NOT NULL
, speed INT(4) UNSIGNED NOT NULL DEFAULT 0
, position INT(4) UNSIGNED NOT NULL DEFAULT 0
, PRIMARY KEY (id)
, UNIQUE INDEX (comp_id, speed, position)
, INDEX (comp_id)
, FOREIGN KEY (comp_id)
REFERENCES competitions (id)
ON DELETE NO ACTION
ON UPDATE CASCADE
) ENGINE=InnoDB CHARACTER SET latin1 COLLATE latin1_swedish_ci;
I want to insert new rows.
INSERT INTO ki (comp_id, speed, position) VALUES (1, 1, 0)
INSERT INTO ki (comp_id, speed, position) VALUES (1, 2, 0)
INSERT INTO ki (comp_id, speed, position) VALUES (1, 3, 0)
INSERT INTO ki (comp_id, speed, position) VALUES (1, 3, 0) -- error
INSERT INTO ki (comp_id, speed, position) VALUES (2, 1, 0)
INSERT INTO ki (comp_id, speed, position) VALUES (2, 3, 0)
INSERT INTO ki (comp_id, speed, position) VALUES (2, 2, 0)
With each comp_id the values of speed begin from 1. The value of speed should always be comp_id's biggest speed value + 1.
In case (1, 3, 0)
already exists, the insert should be (1, max(speed) where comp_id = 1, 0)
. In other words, (1, 4, 0)
.
I do not want to modify the existing rows.
How could I do this on my SQL query? As told, speed must be unique and this has to work if there are several inserts exactly at the same time.
Would the following way work and quarantee an unique speed value (values starting from 1) if there are several inserts at the same time?
INSERT INTO ki (comp_id, speed, position)
VALUES (
1,
COALESCE((SELECT MAX(ki2.speed)
FROM ki AS ki2
WHERE ki2.comp_id = 1
), 1) + 1,
0
)