MySQL 外键关系与 mysql_insert_id 关联表

发布于 2024-12-03 14:51:16 字数 219 浏览 2 评论 0原文

这是为了一种概念验证草案,以使事情正常运行,但不想拥有完全垃圾的代码。对于我的数据库,我尝试使用 innoDB 获得真正的外键关系,但无法获得。

我决定不使用外键,而是在插入后提取 mysql_insert_id(),将其保存为变量,然后将该变量放入相关表中。

这很可怕吗?一切似乎都运行良好,我能够根据需要连接和关联 ID。与我的方法相比,使用外键会给我带来什么好处(除了更新/删除级联)?

This is for a sort of proof of concept draft to get things working, but don't want to have completely crap code. For my database, I tried to get true foreign key relations going using innoDB, but couldn't get it.

Instead of using foreign keys, I decided to just pull mysql_insert_id() after inserts, saving it as a variable, then putting that variable into the related table.

Is this horrible? Everything seems to work well, and I'm able to connect and relate ID's as needed. What benefits would using foreign keys give me over my method (besides updates/deletes cascading)?

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

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

发布评论

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

评论(1

贵在坚持 2024-12-10 14:51:16

要创建关系(主控->详细信息),您必须始终自己提供密钥,可以使用 mysql_insert_id、自然键或应用程序生成的密钥。 FOREIGN KEY 不会让那个为您工作。

FOREIGN KEY 的作用是

  • 帮助您加强数据的关系/完整性(因此“详细”记录不会指向无效的父记录)
  • 处理主记录的删除或键更改(ON DELETE . ..,更新中...)。
  • 如果“master_id”行尚不存在,它还会在“详细信息”表中创建索引(好吧,您也可以在没有 FOREIGN KEY 的情况下执行此操作)
  • 还有某种记录目的,例如 ERM 工具可以根据您的模式重新设计关系模型(好吧,这一点有点遥远)

添加 FOREIGN KEY 约束语句的成本与其好处相比很小。

To create a relation (master->detail), you have to always supply the keys by yourself, either using mysql_insert_id, natural keys or key generated by your applications. The FOREIGN KEY is not going to make that work for you.

What FOREIGN KEY does is

  • Helping you enforce the relationship/the integrity of your data (so the "detail" record does not point to an invalid parent)
  • Handles deletion or key alterations of master records (ON DELETE ..., ON UPDATE ...).
  • It's also creating an index in your "detail"-table for the "master_id"-row if it doesn't exist yet (okay, you could also do that without FOREIGN KEY)
  • Has also some kind of documenting purpose for example an ERM-tool could reengineer the relationship model from your schema (okay, this point is a slight long shot)

The cost of adding the FOREIGN KEY constraint statement is small compared to its benefits.

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