AutoIncrement fields on databases without autoincrement field

后端 未结 5 524
孤街浪徒
孤街浪徒 2020-12-05 12:00

In MS Sql Server is easy create autoincrement fields. In my systems I stopped to use autoincrement fields for primary keys, and now I use Guid\'s. It was awesome, I\'ve got

5条回答
  •  心在旅途
    2020-12-05 12:58

    If you need a non-primary-key autoincrement field, a very nice MySQL only solution for creating arbitraty sequences is to use the relatively unknown last_insert_id(expr) function.

    If expr is given as an argument to LAST_INSERT_ID(), the value of the argument is returned by the function and is remembered as the next value to be returned by LAST_INSERT_ID(). This can be used to simulate sequences...

    (from http://dev.mysql.com/doc/refman/5.1/en/information-functions.html#function_last-insert-id )

    Here is an example which demonstrates how a secondary sequence can be kept for numbering comments for each 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;
    

提交回复
热议问题