父表的 FK 问题
我有这个:
表 A
表 B(从 fk 到 A)
表 C(从 fk 到 B)
表 D(fk 到 C)
现在,当我在表 D 上执行插入/更新/删除时,我假设它将检查表 C 上的 FK,但它会进一步检查父级 A 还是在 C 处停止?一个很好的例子是: 国家->状态->城市->邻里。全部由 FK 连接。那么,如果我对邻居进行 I/U/D 操作,它会检查多远?
这将有助于决定在将数据分解为太多子表之前我可以将数据规范化到什么程度。如果它检查所有表,那么它会减慢系统速度。但如果它只检查直接父级,那么我可以拥有数百个子子表而无需担心。
I have this:
table A
table B (fk to A)
table C (fk to B)
table D (fk to C)
Now when i do Inserts / Updates / Deletes on table D, i assume it will check the FK on table C, but will it further check up right to the parent A or stop at C? A good example is:
Country -> State -> city -> Neighbourhood. All linked by FK. So if i do I/U/D on neighbourhood how far up will it check?
This will help be decide how far I can go with normalizing my data before i break it into too many child tables. If it will check all tables up then it will slow system down. But if it only checks the immediate parent then i can have hundreds of sub-child tables without any worries.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,您在 D 上的插入/更新和删除不会针对 B 和 A 进行检查。该语句只会针对 C 进行检查。但是,您在 C 上的插入已经与 B 进行了检查。因此,间接地您在 D 上的插入将是有效的。
No, your inserts/updates and deletes on D will not be checked against B and A. The statement will only check against C. However you inserts on C would have already been checked with B. Therefore indirectly your inserts on D would be valid.
SqlServer的回答:
当你向表D插入一条记录时,外键检查dRecord中的cID是否在表C中找到。如果在表c中找不到cID,则dRecord将是孤儿记录,并且插入强制失败。
具有该 cID 的 cRecord 在插入时会提前检查其 bID。不需要再次检查。
唯一的“链接”行为是级联删除。如果外键具有级联删除行为,则删除bRecord将删除所有相关的cRecord(具有匹配的bID)以及与这些cRecord(具有匹配的cID)相关的所有dRecord。
Answer for SqlServer:
When you insert a record into table D, the foreign key checks that cID in the dRecord is found in table C. If cID is not found in table c, then the dRecord would be an orphan, and the insert forcefully fails.
The cRecord with that cID had its bID checked earlier, when it was inserted. It does not need to be checked again.
The only "chaining" behavior would be cascade delete. If the foreign keys have cascade delete behavior, deleting a bRecord will delete all related cRecords (with matching bID) and all dRecords related to those cRecords (with matching cID).
数据库应该只需要检查记录 (D) 是否有返回表 C 的外键 - 任何时候您在 C 中插入/更新/删除记录时,都需要验证 B 中是否引用了相应的记录。记录可以在没有与B进行验证的情况下插入C,那么在插入D时,只需要检查C。
无论如何,物理数据建模涉及许多不同的问题。阅读数据建模,例如:Snowflake 和 星形 架构设计数据仓库中的内容是很好的复习参考。
The database should only need to check that the record (D) has a foreign key back to the table C - any time you insert/update/delete a record in C it would need to verify a corresponding record is referenced in B. Since no records can make it into C without having been verified vs B, then when inserting into D, only C would need to be checked.
Regardless, there are a lot of different concerns that go into physical data modeling. Reading about Data Modeling, for example: Snowflake and Star schema designs in Data Warehousing are good references to review.