MYSQL auto_increment_increment [英] MYSQL auto_increment_increment

查看:84
本文介绍了MYSQL auto_increment_increment的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在单个mysql数据库中自动递增两个不同的表,第一个乘以1的倍数,另一个乘以5是可以使用auto_increment功能,因为我似乎只能全局设置auto_increment_increment.

I would like to auto_increment two different tables in a single mysql database, the first by multiples of 1 and the other by 5 is this possible using the auto_increment feature as I seem to only be able to set auto_increment_increment globally.

如果不能选择auto_increment_increment,那么复制此内容的最佳方法是

If auto_increment_increment is not an option what is the best way to replicate this

推荐答案

更新版本:仅使用一个id字段.这很可能不是原子的,因此如果需要并发,请在事务内部使用:

Updated version: only a single id field is used. This is very probably not atomic, so use inside a transaction if you need concurrency:

http://sqlfiddle.com/#!2/a4ed8/1

CREATE TABLE IF NOT EXISTS person (
   id  INT NOT NULL AUTO_INCREMENT,
   PRIMARY KEY ( id )
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

CREATE TRIGGER insert_kangaroo_id BEFORE INSERT ON person FOR EACH ROW BEGIN
  DECLARE newid INT;

  SET newid = (SELECT AUTO_INCREMENT
               FROM information_schema.TABLES
               WHERE TABLE_SCHEMA = DATABASE()
               AND TABLE_NAME = 'person'
              );

  IF NEW.id AND NEW.id >= newid THEN
    SET newid = NEW.id;
  END IF;

  SET NEW.id = 5 * CEILING( newid / 5 );
END;

无效的旧解决方案"(插入前触发器无法看到当前的自动增量值):

Old, non working "solution" (the before insert trigger can't see the current auto increment value):

http://sqlfiddle.com/#!2/f4f9a/1

CREATE TABLE IF NOT EXISTS person (
   secretid  INT NOT NULL AUTO_INCREMENT,
   id        INT NOT NULL,
   PRIMARY KEY ( secretid )
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

CREATE TRIGGER update_kangaroo_id BEFORE UPDATE ON person FOR EACH ROW BEGIN
  SET NEW.id = NEW.secretid * 5;
END;

CREATE TRIGGER insert_kangaroo_id BEFORE INSERT ON person FOR EACH ROW BEGIN
  SET NEW.id = NEW.secretid * 5; -- NEW.secretid is empty = unusuable!
END;

这篇关于MYSQL auto_increment_increment的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆