Auto-Increment with Grouping in MySQL (5.0)
When working with relational databases, it can be beneficial to have an auto-increment field that is grouped by a specific column. This can provide a sequential order within each group, making data manipulation and analysis more efficient.
In MySQL version 5.0, there is a method to achieve auto-increment by group using MyISAM or BDB table types. By creating a secondary part of the primary key as an auto-increment field, you can ensure that the auto-increment value is unique within each group.
Structure:
<code class="sql">CREATE TABLE foo ( id INT AUTO_INCREMENT NOT NULL, group_field INT NOT NULL, name VARCHAR(128), PRIMARY KEY(group_field, id) );</code>
Explanation:
The auto-increment value is calculated as follows:
MAX(id) + 1 WHERE group_field=given-group
This ensures that when inserting new records into the table, the id field will automatically increment within the specified group.
The above is the detailed content of How Can I Implement Auto-Increment with Grouping in MySQL 5.0?. For more information, please follow other related articles on the PHP Chinese website!