Emulating a transaction-safe SEQUENCE in MySQL

后端 未结 4 2164
不思量自难忘°
不思量自难忘° 2020-12-08 23:33

We\'re using MySQL with InnoDB storage engine and transactions a lot, and we\'ve run into a problem: we need a nice way to emulate Oracle\'s SEQUENCEs in MySQL. The requirem

4条回答
  •  清歌不尽
    2020-12-09 00:21

    We are a high transaction gaming company and need these sort of solutions for our needs. One of the features of Oracle sequences was also the increment value that could also be set.

    The solution uses DUPLICATE KEY.

    CREATE TABLE sequences (
      id BIGINT DEFAULT 1,
      name CHAR(20),
      increment TINYINT,
      UNIQUE KEY(name)
    );
    

    To get the next index:

    Abstract the following with a stored procedure or a function sp_seq_next_val(VARCHAR):

    INSERT INTO sequences (name) VALUES ("user_id") ON DUPLICATE KEY UPDATE id = id + increment;
    SELECT id FROM sequences WHERE name = "user_id";

提交回复
热议问题