Background: As required by the project, you must use mysql to set the primary key to auto-increment and use a string. After searching online and experimenting, I finally made a set of solutions. Share it with you now! Solution: because mysql does not contain sequence, you need to manually create a table (tb_sequence) for storing sequence, insert a piece of data manually, and finally
Background: As required by the project, you must use mysql to set the primary key to auto-increment and use a string. After searching online and experimenting, I finally made a set of solutions. Share it with you now! Solution: because mysql does not contain sequence, you need to manually create a table (tb_sequence) for storing sequence, insert a piece of data manually, and finally
Background: As required by the project, you must use mysql to set the primary key to auto-increment and use a string. After searching online and experimenting, I finally made a set of solutions. Share it with you now!
Solution: because mysql does not contain sequence, you need to manually create a table (tb_sequence) for storing sequence, and then insert a data record manually, finally, define a function to process the value to be increased.
Do it together:
1. Create a table tb_sequence to store the sequence value:
[SQL]View plaincopyprint?
- Create table tb_sequence (name varchar (50) not null, current_value int not null, _ increment int not null default 1, primary key (name ));
2. manually insert data:
[SQL]View plaincopyprint?
- Insert into tb_sequence values ('userid', 100,2 );
3. Define function _ nextval:
[SQL]View plaincopyprint?
- DELIMITER //
- Create function _ nextval (n varchar (50) returns integer
- Begin
- Declare _ cur int;
- Set _ cur = (select current_value from tb_sequence where name = n );
- Update tb_sequence
- Set current_value = _ cur + _ increment
- Where name = n;
- Return _ cur;
- End;
- //
Description: delimiter // ----> defines the statement Terminator. See other code for yourself.
4. Restore the default statement Terminator: (this can be omitted, but the Terminator must be //. It should be set back for convenience .)
[SQL]View plaincopyprint?
- DELIMITER;
5. Inspection Results
Run the following statement multiple times:
[SQL]View plaincopyprint?
- Select _ nextval ('userid ');
Result:
[SQL]View plaincopyprint?
- Mysql> select _ nextval ('userid ');
- + -------------------- +
- | _ Nextval ('userid') |
- + -------------------- +
- | 1, 102 |
- + -------------------- +
- 1 row in set (0.00 sec)
-
- Mysql> select _ nextval ('userid ');
- + -------------------- +
- | _ Nextval ('userid') |
- + -------------------- +
- | 1, 104 |
- + -------------------- +
- 1 row in set (0.00 sec)
-
- Mysql> select _ nextval ('userid ');
- + -------------------- +
- | _ Nextval ('userid') |
- + -------------------- +
- | 1, 106 |
- + -------------------- +
- 1 row in set (0.00 sec)
6. The experiment is over.