Suppose we are building a GitHub and we have two tables: repos and issues . Each GitHub repository has a set of problems, so the issues table has a foreign key repo_id .
Now that you are viewing the GitHub repo issues, you do not want them to appear in the internal id . Instead, you need something like number , which increments from 1..n only for this repository. You want your first problem in your new repo to be numbered 1 , not the next id for the problem with GitHub.
Of course, you need a way to increase, and you want to make sure that number is unique when binding to a repo. And therefore, you especially want to avoid any race conditions where the same number can be generated twice.
What is the easiest way to handle this? Trigger? Is something else completely?
I use PostgreSQL, but prefer approaches that are vanilla SQL where possible, for example. triggers. If there is a simpler Postgres approach then this will also be useful.
Any code demonstrating your approach will be extremely helpful. Thanks!
source share