Group by value to implement automatic increment of custom SERIAL
Challenge:
In a blog system, you have an article table with three columns: id (sequence), category (varchar) and category_id (int). You want the category_id to automatically increment within each category while remaining unique across the table.
Invalidity of custom logic:
Trying to implement this using two separate queries and logic code may cause concurrency issues in a multi-user environment.
Recommended solution:
Discard category_id column:
Dynamic calculation of category position:
<code class="language-sql">SELECT id, category, ROW_NUMBER() OVER (PARTITION BY category ORDER BY id) AS category_id FROM article;</code>
Example:
<code class="language-sql">INSERT INTO article(category) VALUES ('stackoverflow');</code>
Result:
<code>SELECT * FROM article WHERE category = 'stackoverflow'; +----+-----------+---------+ | id | category | category_id | +----+-----------+---------+ | 10 | stackoverflow | 1 | | 11 | stackoverflow | 2 | +----+-----------+---------+</code>
The above is the detailed content of How to Implement Custom SERIAL Auto-Increment within Categories in a Database?. For more information, please follow other related articles on the PHP Chinese website!