I have a column tracking unique user_id
by project (for external use).
I want to increment the user_id
column when creating a new user, subject to whatever the count is at for that project. There are many existing records already, but from here on out we want the user_id
to increment up by 1 for each new record in a given project_id
.
Example User table
id user_id project_id
-------------------------
1 100 1
2 101 1
3 1000 2
4 1001 2
5 17 3
6 18 3
7 102 1
New row with project_id = 1 should use user_id = 103
New row with project_id = 2 should use user_id = 1002
New row with project_id = 3 should use user_id = 19
How can I construct the user_id
column and/or INSERT
query such that it will always increment the user_id
based on the largest existing user_id
within the corresponding project_id
, and guarantee that no two users in the same project are assigned the same user_id
upon concurrent inserts?