MySQL equivalent of Oracle's SEQUENCE.NEXTVAL

前端 未结 7 1349
无人及你
无人及你 2020-12-01 11:13

I need to be able to generate run a query that will return the next value of ID on the following table:

CREATE TABLE animals (
     id MEDIUMINT NOT NULL AUT         


        
相关标签:
7条回答
  • 2020-12-01 11:51

    This example with InnoDB demonstrates a way to implement your own counter using interlocked queries:

    http://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html

    What do you need to create a gap for? To reserve IDs? I'd rather "fix" the design at all costs and update the other modules instead of touching a sequence.

    Instead of just incrementing the sequence explicitly, I'd imply it by inserting a default row (marked invalid) for each id to allocate and return the id. This approach is consistent and portable. Later, instead of forcing inserts using an explicit sequence value, you can update these default rows by their matching sequence values. This requires more memory but no locks. Garbage collection on expired rows can help here. 'insert or update' statements can recreate garbage collected rows, I wouldn't do this though.

    0 讨论(0)
提交回复
热议问题