Using Sequence Generators as Counters
Problem
You’re interested only in counting events, so there’s no point in creating a table row for each sequence value.
Solution
Use a sequence-generation mechanism that uses just one row per counter.
Discussion
AUTO_INCREMENTcolumns are useful for generating sequences across a set
of individual rows. But for some applications, you’re interested only
in a count of the number of times an event occurs, and there’s no
value in creating a separate row for each event. Instances include web
page or banner ad hit counters, a count of items sold, or the number
of votes in a poll. For such applications, you need only a single row
to hold the count as it changes over time. MySQL provides a mechanism
for this that enables counts to be treated like AUTO_INCREMENT values so that you can not
only increment the count, but retrieve the updated value
easily.
To count a single type of event, you can use a trivial table with a single row and column. For example, if you’re selling copies of a book, you can create a table to record sales for it like this:
CREATE TABLE booksales (copies INT UNSIGNED);
However, if you’re counting sales for multiple book titles, that
method won’t work so well. You certainly don’t want to create a
separate single-row counting table per book. Instead, you can count
them all within a single table if you include a column that provides a
unique identifier for each book. The following table, booksales, does this using a title column for the book ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access