I have users
table and posts
table. A user has many posts.
CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(10));
CREATE TABLE posts (id INT, user_id INT, text TEXT, PRIMARY KEY(id, user_id));
My question is, How do I create an automatically increment mechanism to increment the id
of a user's post but scoped to the user (the user_id
) only.
For example,
user 1
has 2 posts, the first post has id 1
, the second post has id 2
.
user 2
has 3 posts, the first post has id 1
, the second post has id 2
, the third post has id 3
.
The rows of the posts
table will look like this.
SELECT * FROM posts;
user_id id text
1 1 'Post one from user 1'
2 1 'Post one from user 2'
2 2 'Post two from user 2'
2 3 'Post three from user 2'
1 2 'Post two from user 1'
I know this can be done by implementing it on the application level on two trips to the database, such as querying the last post id of a particular user and creating the post based on that. But this can introduce collision in a multi-user environment.