Say I have two tables, users and groups each of which has an auto-incrementing primary key. Whenever a new user is created, I would like to create a group along with that user (at the same time/same transaction). However, the users need to know which group they belong to thus each user stores a group_id.
In order to do this, I create and insert a group into the database, find out what the primary key of that group I just inserted was, and finally insert the user with that new group's primary key.
Note that I need to commit the group to the database (thus having it outside any transaction with committing the user as well) in order to retrieve the primary key it was assigned.
Although this will work in most situations, if there is some kind of failure (power failure, system crash, etc.) between when I insert the group and find out its primary key, and when I insert the user, I will end up with an inconsistent database.
Is there a way to do something like reserving a primary key temporarily so that if the system crashes, it won't end up in an inconsistent state?
I'm primarily concerned with MySQL databases but if there is something in standard SQL which will allow me to do this (and is thus, compatible with other database backends), I'm also interested in knowing that.