Oracle数据库可以使用序列(Sequence),而MySQL不支持序列,MySQL只支持主键自增。
方法一:Oracle序列直接转化为MySQL主键自增
MySQL代码如下:
alter table user modify id integer auto_increment ;
其中:user为表名;
id为主键
在数据库工具中也可以设置(navicat):
设置主键自增后,sql代码也要修改:
原Oracle:
insert into user values(seq_user.nextval,'我是加加加Oracle1');
insert into user values(seq_user.nextval,'我是加加加Oracle2');
转化为MySQL:
insert into user values(null,'我是加加加MySQL1');
insert into user values(null,'我是加加加MySQL2');
在自增位置插入null值,得到的结果就会自增
方法二:在MySQL中建一个函数模仿序列,然后把当前序列的值存在一个表中:
drop table if exists sequence;
CREATE TABLE IF NOT EXISTS sequence (
seq_name varchar(50) NOT NULL, -- 序列名称
current_value int DEFAULT NULL, -- 当前值
increment int NOT NULL DEFAULT '1' -- 自增值
)
插入一条记录:(相当于增加一个序列,Oracle中有多少序列,就插入多少记录)
INSERT INTO sequence VALUES ('seq_demo', '0', '1'); -- seq_demo为原Oracle序列名
编写一个函数,来模拟序列:(意思就是调用一次这个函数,“序列的值”自增“1”)
DROP function IF EXISTS nextval;
create function nextval (v_seq_name VARCHAR(50))
returns integer
begin
update sequence set current_value = current_value + increment where seq_name = v_seq_name;
return (select current_value from sequence where seq_name = v_seq_name);
end;
执行sql
select nextval('序列名')
每执行一次,就会自增1。