Home > Database > Mysql Tutorial > body text

Use mysql to generate unique serial numbers

藏色散人
Release: 2020-03-16 08:51:44
forward
3969 people have browsed it

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;
Copy after login

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();
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template