How to create a sequence in mysql

If you don't want to use mysql's auto-increment, but want to implement the function of the primary key serial number, you can use the following method to use a table to maintain the serial number of multiple tables through the function, which is simple and practical
    
1. Create and generate multiple Table serial number data maintenance table
CREATE TABLE seq (
  name varchar(20) NOT NULL,
  val int(10) UNSIGNED NOT NULL,
  PRIMARY KEY (name)
) ENGINE=MyISAM DEFAULT CHARSET=UTF-8

2. Insert several initializations data
INSERT INTO seq VALUES('one',100);
INSERT INTO seq VALUES('two',1000);

3. Create function to generate sequence number
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. Test
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)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326887472&siteId=291194637