Se è necessario un campo di autoincrement non primario, una soluzione MySQL molto utile per la creazione di sequenze arbitrarie è l'uso della funzione relativamente sconosciuta last_insert_id(expr)
.
Se espressione è data come argomento LAST_INSERT_ID(), il valore dell'argomento viene restituito dalla funzione ed è ricordato come il valore accanto a essere restituito da LAST_INSERT_ID(). Questo può essere utilizzato per simulare le sequenze ...
(da http://dev.mysql.com/doc/refman/5.1/en/information-functions.html#function_last-insert-id)
Ecco un esempio che dimostra come una sequenza secondaria può essere mantenuto per la numerazione commenti per ogni post:
CREATE TABLE `post` (
`id` INT(10) UNSIGNED NOT NULL,
`title` VARCHAR(100) NOT NULL,
`comment_sequence` INT(10) UNSIGNED NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
);
CREATE TABLE `comment` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`post_id` INT(10) UNSIGNED NOT NULL,
`sequence` INT(10) UNSIGNED NOT NULL,
`content` TEXT NOT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO post(id, title) VALUES(1, 'first post');
INSERT INTO post(id, title) VALUES(2, 'second post');
UPDATE post SET comment_sequence=Last_insert_id(comment_sequence+1) WHERE id=1;
INSERT INTO `comment`(post_id, sequence, content) VALUES(1, Last_insert_id(), 'blah');
UPDATE post SET comment_sequence=Last_insert_id(comment_sequence+1) WHERE id=1;
INSERT INTO `comment`(post_id, sequence, content) VALUES(1, Last_insert_id(), 'foo');
UPDATE post SET comment_sequence=Last_insert_id(comment_sequence+1) WHERE id=1;
INSERT INTO `comment`(post_id, sequence, content) VALUES(1, Last_insert_id(), 'bar');
UPDATE post SET comment_sequence=Last_insert_id(comment_sequence+1) WHERE id=2;
INSERT INTO `comment`(post_id, sequence, content) VALUES(2, Last_insert_id(), 'lorem');
UPDATE post SET comment_sequence=Last_insert_id(comment_sequence+1) WHERE id=2;
INSERT INTO `comment`(post_id, sequence, content) VALUES(2, Last_insert_id(), 'ipsum');
SELECT * FROM post;
SELECT * FROM comment;
Suggerirei di riscrivere il titolo in qualcosa che sia un po 'più chiaro come "Creazione di campi di autoincremento indipendenti dal database". La mia preoccupazione è che non penso che troverei il tuo titolo quando farei una ricerca per lo stesso argomento. – Elijah
Hai davvero bisogno di un numero in continuo aumento, o hai solo bisogno di unicità? –
Sì, ho bisogno di "un numero a incremento continuo", per altre situazioni utilizzo guids, CRC, ecc ... –