How to generate a dynamic sequence table in MySQL?

后端 未结 1 355
攒了一身酷
攒了一身酷 2020-12-07 05:46

I\'m trying to generate a sequence table in MySQL, so that I can get unique ids from last_insert_id.

The problem is that I need multiple sequences dynam

相关标签:
1条回答
  • 2020-12-07 06:28

    The MyISAM engine will do it for you -

    Table definition:

    CREATE TABLE `sequence` (
      `label` char(30) CHARACTER SET latin1 NOT NULL,
      `id` mediumint(9) NOT NULL AUTO_INCREMENT,
      PRIMARY KEY (`label`,`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
    

    Populate table:

    INSERT INTO sequence VALUES ('a', NULL); -- add some 'a' labels
    INSERT INTO sequence VALUES ('a', NULL);
    INSERT INTO sequence VALUES ('a', NULL);
    
    INSERT INTO sequence VALUES ('b', NULL); -- add another labels 'b'
    INSERT INTO sequence VALUES ('b', NULL);
    
    INSERT INTO sequence VALUES ('a', NULL); -- add some 'a' labels
    INSERT INTO sequence VALUES ('a', NULL);
    

    Show result:

    SELECT * FROM sequence;
    +-------+----+
    | label | id |
    +-------+----+
    | a     |  1 |
    | a     |  2 |
    | a     |  3 |
    | a     |  4 |
    | a     |  5 |
    | a     |  6 |
    | b     |  1 |
    | b     |  2 |
    +-------+----+
    
    0 讨论(0)
提交回复
热议问题