在联结表中进行编辑的最佳做法是什么?
Items{ItemId, Name, Price...}
Shops{ShopId, Name, Address...}
ItemsInShops{ItemId, ShopId, DeliveryDate...}
现在我在一个商店里有 30 件商品。我想编辑该列表并取消选中 10 个项目并选中 50 个新项目。
我按以下方式执行此操作:通过“ItemId”从“ItemsInShops”中删除所有行并添加新值。我不认为这是好的解决方案。有没有更好的方法来进行这种更新?
也许我没有用好的例子表达问题。看看这个:
User{UserId, Username, Password...}
Roles{RoleId, Name, Description} // Admin, Member, Superuser, Junior etc
UsersInRoles{UserId,RoleId}
用户可以拥有任意数量的角色。
John > Admin, Member, Superuser
这是联结表“UserInRoles”中的三行。 如果我想将此用户更新为具有以下角色:
John > Member, Junior
现在我通过以下方式对数据库进行更新: 我从“UserInRoles”表中删除所有 John 角色并添加新数据。我不知道除了全部删除并插入新的之外还有什么更好的方法来进行此更新?如果由于某种原因(例如失去互联网连接)更新失败怎么办?
最佳答案
I don't know is there any better way to do this update, other than delete all and insert new?
您不必一开始就删除所有行。
您可以只删除不再适用的行,只插入新的行。或者,您可以将不再适用的值更新为适用的值。
所以要从这里得到
Name Role
--
John Admin
John Member
John Superuser
对此
Name Role
--
John Member
John Junior
您可以删除不再适用的内容。 . .
delete from userinroles
where Name = 'John'
and (Role = 'Admin' or Role = 'Superuser');
并插入适用的内容。
insert into userinroles (Name, Role)
values ('John', 'Junior');
或者您可以使用新值更新值。
delete from userinroles
where Name = 'John'
and Role = 'Admin';
紧随其后
update userinroles
set Role = 'Junior'
where 'Name' = 'John' and Role = 'Superuser';
你说
What if update fails from some reason (lost internet connection for example)?
这就是交易的目的。单个 SQL 事务中的多个语句是全有或全无 - 它们要么全部成功,要么不进行任何更改。
关于mysql - 如何在联结表中执行编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39694526/