在server.xml中,将sequnceHandlerType设置为1
1
在schema.xml中,table中增加属性autoIncrement值为true,添加mycat_sequence表
在sequence_db_conf.properties中,依赖全局序列,增加序列,与table名称相同全大写
TT2=dn20
创建mycat_sequence表,在dn20对应的数据库下面创建。
DROP TABLE IF EXISTS MYCAT_SEQUENCE;
CREATE TABLE MYCAT_SEQUENCE(
name VARCHAR(50) NOT NULL,
current_value INT NOT NULL,
increment INT NOT NULL DEFAULT 100,
PRIMARY KEY(name)
) ENGINE=InnoDB;
name:sequence名称(表明)
currenct_value:当前value(当前值)
increment:增长步长(增长步长)
注:MYCAT_SEQUENCE必须大写
插入sequence记录
INSERT INTO MYCAT_SEQUENCE(name, current_value, increment) VALUES (TT2, 1, 100);
创建存储函数,必须在同一个数据库中创建,也就是在dn20对应的zhaimi库创建。
获取当前sequence的值 (返回当前值,增量)
DROP FUNCTION IF EXISTS mycat_seq_currval;
DELIMITER ;;
CREATE FUNCTION mycat_seq_currval(seq_name VARCHAR(50)) RETURNS varchar(64) CHARSET utf8
DETERMINISTIC
BEGIN
DECLARE retval VARCHAR(64);
SET retval="-999999999,null";
SELECT concat(CAST(current_value AS CHAR),",",CAST(increment AS CHAR)) INTO retval FROM MYCAT_SEQUENCE WHERE name = seq_name;
RETURN retval;
END ;;
DELIMITER ;
设置sequence值
DROP FUNCTION IF EXISTS mycat_seq_setval;
DELIMITER ;;
CREATE FUNCTION mycat_seq_setval(seq_name VARCHAR(50),value INTEGER) RETURNS varchar(64) CHARSET utf8
DETERMINISTIC
BEGIN
UPDATE MYCAT_SEQUENCE
SET current_value = value
WHERE name = seq_name;
RETURN mycat_seq_currval(seq_name);
END ;;
DELIMITER ;
获取下一个sequence值
DROP FUNCTION IF EXISTS mycat_seq_nextval;
DELIMITER ;;
CREATE FUNCTION mycat_seq_nextval(seq_name VARCHAR(50))
RETURNS varchar(64) CHARSET utf8
DETERMINISTIC
BEGIN
UPDATE MYCAT_SEQUENCE
SET current_value = current_value + increment
WHERE name = seq_name;
RETURN mycat_seq_currval(seq_name);
END ;;
DELIMITER ;
在mysql中定义自增主键
CREATE TABLE tt2 (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
nm INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (id)
) ENGINE=MYISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
插入记录
insert into tt2(nm) values (99);
FROM:
1.MyCAT自增字段和返回生成的主键ID的经验分享
2.MyCAT 性能测试
3.mycat分布式mysql中间件(自增主键)
4.MyCAT全局序列号
批量整理配置文件和表的脚本
整理配置文件
select CONCAT(upper(TABLE_NAME),'=dn20') from TABLES where TABLE_SCHEMA='zhaimi';
整理表内容
select CONCAT('insert into mycat_sequence(name,current_value,increment) values("',upper(TABLE_NAME),'",(select max(id) from ',upper(TABLE_NAME),'),100);')
from TABLES where TABLE_SCHEMA='zhaimi';
查看表内容
SELECT * from mycat_sequence;
测试
desc zm_audits;
插入数据
insert into zhaimi.zm_audits ( user_agent, operator_type, operand_id, params, operation_desc, created_at, updated_at, ip, operator_id) values ( 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.89 Safari/537.36', 'MERCHANT', '301', '{\"scope\":\"merchant\",\"grant_type\":\"password\",\"name\":\"ceshiceshi\",\"password\":\"cesh\"}', 'LOGIN', '2015-07-29 12:39:24', '2015-07-29 12:39:24', '3031268088', '301');
查看数据是否插入
select * from zhaimi.zm_audits where created_at='2015-07-29 12:39:24';