Using an AUTO_INCREMENT Column to Create Multiple Sequences
Problem
You need to have sequencing behavior that is more complex than a single sequence of values. You need to tie different sequences to the values in other columns of the table.
Solution
Link the AUTO_INCREMENT
column to those other columns, making them all part of the same
index.
Discussion
When an AUTO_INCREMENT
column
is the only column in a
PRIMARY
KEY
or
UNIQUE
index, it
generates a single sequence 1, 2, 3, ... in which successive values
increase by one each time you add a row, regardless of the contents of
the rest of the row. For MyISAM or BDB tables, it’s possible to create
an index that combines an AUTO_INCREMENT
column with other columns to
generate multiple sequences within a single table.
Here’s how it works: let’s say that Junior develops such a passion for bug collecting that he decides to keep it up even after the school project has been completed—except that when freed from the constraints of the teacher’s instructions, he’s perfectly content to include insect-like bugs such as millipedes, and even to collect multiple instances of any given creature. Junior happily goes outside and collects more specimens over the next few days:
Name | Date | Origin |
---|---|---|
ant | 2006-10-07 | kitchen |
millipede | 2006-10-07 | basement |
beetle | 2006-10-07 | basement |
ant | 2006-10-07 | front yard |
ant | 2006-10-07 | front yard |
honeybee | 2006-10-08 | back yard |
cricket | 2006-10-08 | garage |
beetle | 2006-10-08 | front yard |
termite | 2006-10-09 | kitchen woodwork |
cricket | 2006-10-10 | basement |
termite | 2006-10-11 ... |
Get MySQL Cookbook, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.