1.创建生成多个表的序列号的数据维护表
- CREATE TABLE `seq` (
- `name` varchar(20) NOT NULL,
- `val` int(10) unsigned NOT NULL,
- PRIMARY KEY (`name`)
- ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
2.插入几条初始化数据
- INSERT INTO seq VALUES('one',100);
- INSERT INTO seq VALUES('two',1000);
3.创建函数以生成序列号
- 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
4.测试
- mysql> SELECT seq( 'one' ) ,seq( 'two' ) ,seq( 'one' ) ,seq( 'one' ) ;
-
+ ------------+------------+------------+------------+
- | seq( 'one' ) | seq( 'two' ) | seq( 'one' ) | seq( 'one' ) |
-
+ ------------+------------+------------+------------+
- | 102 | 1002 | 103 | 104 |
-
+ ------------+------------+------------+------------+
- 1 row IN SET ( 0 .00 sec)