MySQL序列解决方案


最近公司项目从Oracle向MySQL移植,遇到的第一个问题就是MySQL没有序列。

MySQL能够把字段设置为自增长,写法为:

view plaincopy to clipboardprint?
create table test  
(  
  id int auto_increment primary key  

create table test
(
  id int auto_increment primary key
)

自增字段只能是primary key,插入数据时自增字段不要设值或把值设成NULL就能实现自增长了。

view plaincopy to clipboardprint?
# INSERT INTO test (name) VALUES ('Gladiator');   
# INSERT INTO test (id,name) VALUES (NULL,'The Bourne Identity'); 
# INSERT INTO test (name) VALUES ('Gladiator'); 
# INSERT INTO test (id,name) VALUES (NULL,'The Bourne Identity');

但是这种自增长只能用于某个表的某个字段,要实现像oracle那样的序列功能要用到存储过程

view plaincopy to clipboardprint?
CREATE TABLE `seq` (  
  name varchar(20) NOT NULL,  
  val int(10) UNSIGNED NOT NULL,  
  PRIMARY KEY  (name)  
) ENGINE=MyISAM DEFAULT CHARSET=latin1  
CREATE FUNCTION seq(seq_name char (20)) returns int 
begin  
UPDATE seq SET val=last_insert_id(val+1) WHERE name=seq_name;  
RETURN last_insert_id();  
end  
INSERT INTO seq VALUES('one',1000);  
select seq('one'); 

相关内容