Two tables share a unique identifier ‘id’. Both tables are meant to be joined by using ‘id’.
Defining ‘id’ as an auto incrementing primary key in both tables may risk update inconsistencies.
Is there some general pattern to avoid such a situation or do I have to deal with updating table1 first and table2 by utilizing the last inserted id after (therefore not declaring id as auto inc in table2)?
First, if you use InnoDB table engine in MySQL you could use both transactions and foreign keys for data consistency.
Second, after the insert in the first table, you could get the last insert id (depending on the way you access the db) and use it as foreign key.
Eg
Table 1:
Users:user_id, usernameTable 2:
User_Profiles:user_id, name, phoneIn User_Profiles you don’t need to define
user_idas auto increment, but first insert a record inUserstable and use theuser_idfor theUser_Profilesrecord. If you do this in transaction, theUsersrecord won’t be seen outside of the transaction connection until it’s completed, this way you guarantee that even if something bad happens after you insert the user, but before you have inserted the profile – there won’t be messed up data.You could also define that the
user_idcolumn inUser_Profilestable is foreign key ofUserstable thus if someone deletes a record from theUserstable, the database would automatically delete the one inUser_Profiles. There are many other options – read more about that.