Home>Article>Database> Use mysql to generate unique serial numbers

Use mysql to generate unique serial numbers

藏色散人
藏色散人 forward
2020-03-16 08:51:44 3902browse

When the database is divided into tables or the program itself needs a unique ID, we need a solution to generate a unique ID.

You can write a program that combines time and certain characteristics to generate a unique ID. You can also consider using the feature of auto-incrementing IDs in the database to achieve this requirement. Here is an example of mysql.

First create a table that specifically generates ids, where the id field is the primary key and the replace_key field is the unique key.

CREATE TABLE `ticket` ( `id` bigint(20) unsigned NOT NULL auto_increment, `replace_key` char(1) NOT NULL default '', PRIMARY KEY (`id`), UNIQUE KEY `replace_key` (`replace_key`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=10001;

Every time you need to generate an id, use the replace into statement to generate a new record, replace the old record, and then return the id.

REPLACE INTO `ticket` (`replace_key`) VALUES ('a'); SELECT LAST_INSERT_ID();

Recommended mysql video tutorial, address://m.sbmmt.com/course/list/51.html

The above is the detailed content of Use mysql to generate unique serial numbers. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete