MySQL serial number generator)

Source: Internet
Author: User

If you do not want to use MySQL auto-increment, but want to implement the primary key serial number function, you can use the following method to maintain the serial number of multiple tables using a function, simple and practical

1. Create a Data Maintenance table that generates the serial numbers of multiple tables

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 initialization data entries

Insert into seq values ('one', 100 );
Insert into seq values ('two', 1000 );

3. Create a function to generate a serial 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

  1. Mysql>SelectSeq('One'), Seq('Two'), Seq('One'), Seq('One');
  2. +------------ +
  3. | Seq('One')| Seq('Two')| Seq('One')| Seq('One')|
  4. +------------ +
  5. |102|1002|103|104|
  6. +------------ +
  7. 1RowIn Set (0.00Sec)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.