Home > Database > Mysql Tutorial > How to Achieve Auto-Incrementing by Groups in MySQL?

How to Achieve Auto-Incrementing by Groups in MySQL?

Patricia Arquette
Release: 2024-10-31 12:33:02
Original
575 people have browsed it

How to Achieve Auto-Incrementing by Groups in MySQL?

Auto-Incrementing by Groups in MySQL

MySQL users occasionally face the need to assign auto-incrementing values to rows based on a specific grouping column. For example, consider a table containing records with columns for id, name, and group_field.

To achieve auto-incrementing by group, one can utilize a strategy involving creating a secondary part of the key for MyISAM and BDB tables:

CREATE TABLE foo (
   id          INT AUTO_INCREMENT NOT NULL,
   group_field INT NOT NULL,
   name        VARCHAR(128),

   PRIMARY KEY(group_field, id)
);
Copy after login

As per the MySQL manual, the auto-increment value for the 'id' column is determined using the formula:

MAX(auto_increment_column) 1 WHERE prefix=given-prefix

where 'prefix' corresponds to the value in the 'group_field' column. This approach proves particularly useful for organizing data into sequential groups.

The above is the detailed content of How to Achieve Auto-Incrementing by Groups in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template