更新数据库中的一对多关系数据

发布于 2024-10-27 03:47:24 字数 278 浏览 3 评论 0原文

我想更新数据库中具有一对多关系的列表。

例如,有超过100个科目,学生可以选择任何他想要的科目。假设下次该学生编辑他的选择。

对于这种情况,您将如何更新数据库?我习惯做的是删除所有过去的选择并添加所有新选择的主题。这是非常简单的逻辑,但我只是想知道在性能方面是否有更好的方法来做到这一点。在我的例子中,“删除”是单个数据库调用,而插入全部是单个数据库连接中的循环。

我知道我们可以添加一个逻辑来识别已删除的记录和新添加的记录。真的值得这样做吗?对于类似的情况你会怎么做?

谢谢!

I want to update a list in the database which has one to many relationship.

For example, There are over 100 subjects and a student can select whatever he wants. Let's say next time that student edit his selection.

What is the way you would update the database for this case? What I am used to doing is delete all the past selections and add all the newly selected subjects. This is pretty easy logic but I am just wondering whether there is a better way to do this in terms of performance. In my case 'delete' is a single database call and inserting all is a loop in a single database connection.

I understand we can add a logic to identify the deleted records and newly added records. Is it realy worth to do that? What you would do for similar cases?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

油饼 2024-11-03 03:47:24

为了简洁起见,删除重新插入方法并没有什么问题,禁止子表中的外键挂钩或每次(重新)插入时触发触发器。

另一种方法是将新集作为表值参数传递给 Sql Server 的 SP,然后 SP 将使用一组查询来进行更改

delete many_table
where studentid=@studentid and someid not in (select someid from @tableparam p)

insert many_table(studentid, someid)
select @studentid, p.someid
from @tableparam p left join many_table t on p.someid=t.someid and t.studentid=@studentid
where t.someid is null

(SQL Server 2008 有一种更优雅的 MERGE 语法,这是另一个选项,进一步测试您的 TSQL 技能)

For brevity and simplicity, there is nothing really wrong with a delete-reinsert approach, barring foreign key hooks from child tables or triggers firing for each (re)insert.

Another way to do it could be to pass the new set as a table-valued parameter to a SP to Sql Server, which would then use a duo of queries to make the change

delete many_table
where studentid=@studentid and someid not in (select someid from @tableparam p)

insert many_table(studentid, someid)
select @studentid, p.someid
from @tableparam p left join many_table t on p.someid=t.someid and t.studentid=@studentid
where t.someid is null

(there is a more elegant MERGE syntax for SQL Server 2008, which is yet another option, further testing your TSQL skills)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文