I'm trying to make a blog system of sort and I ran into a slight problem.
Simply put, there's 3 columns in my article
table:
id SERIAL,
category VARCHAR FK,
category_id INT
id
column is obviously the PK and it is used as a global identifier for all articles.
category
column is well .. category.
category_id
is used as a UNIQUE
ID within a category so currently there is a UNIQUE(category, category_id)
constraint in place.
However, I also want for category_id
to auto-increment.
I want it so that every time I execute a query like
INSERT INTO article(category) VALUES ('stackoverflow');
I want the category_id
column to be automatically be filled according to the latest category_id
of the 'stackoverflow' category.
Achieving this in my logic code is quite easy. I just select latest num and insert +1 of that but that involves two separate queries.
I am looking for a SQL solution that can do all this in one query.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…