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: https://www.php.cn/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!