What is the best practice to make edit in junction tables?
Items{ItemId, Name, Price...}
Shops{ShopId, Name, Address...}
ItemsInShops{ItemId, ShopId, DeliveryDate...}
Now I have 30 items in one shop. I want to edit that list and I uncheck 10 items and check 50 new items.
I do this in the following way: Remove all rows from ‘ItemsInShops’ by ‘ItemId’ and add new values. I don’t think that this is good solution. Is there any better way to do this kind of update?
Maybe I didn’t express problem with good example. Take a look at this:
User{UserId, Username, Password...}
Roles{RoleId, Name, Description} // Admin, Member, Superuser, Junior etc
UsersInRoles{UserId,RoleId}
User can have any number of roles.
John > Admin, Member, Superuser
That is three rows in junction table ‘UserInRoles’.
If I want to update this user to have the following roles:
John > Member, Junior
Now I do this update on database in the following way:
I remove all John roles from ‘UserInRoles’ table and add new data. I don’t know is there any better way to do this update, other than delete all and insert new? What if update fails from some reason (lost internet connection for example)?
You don’t have to delete all the rows to start with.
You can delete only the rows that no longer apply, and insert only the rows that are new. Or you can update a value that no longer applies with a value that does apply.
So to get from this
to this
You can delete what no longer applies . . .
and insert what does apply.
Or you can update a value with a new value.
Followed by
You said
That’s what transactions are for. Multiple statements within a single SQL transaction are all or nothing–either they all succeed, or no changes are made.