如果您需要一个非主键自动增量字段,一个非常好的 MySQL 唯一用于创建任意序列的解决方案是使用相对未知的last_insert_id(expr)
函数。
如果 expr 作为 LAST_INSERT_ID() 的参数给出,则参数的值由函数返回,并作为 LAST_INSERT_ID() 返回的下一个值被记住。这可以用来模拟序列...
(来自http://dev.mysql.com/doc/refman/5.1/en/information-functions.html#function_last-insert-id)
这是一个示例,它演示了如何为每个帖子的评论编号保留二级序列:
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;