自动索引的 SQL Server 2008 外键
SQL Server 2008 中的外键是否会自动使用值进行索引?例如。如果我在可能的父表中的主键(或自动递增)中添加一个值,具有引用该键的外键的表将自动具有相同的值吗?或者我必须明确地这样做?
Are Foreign Keys in SQL Server 2008 are automatically indexed with a value? For Example. if I add a value in my Primary key (or auto incremetend) in may parent table will the table that has a foreign key referenced to that key will automatically have the same value? or I Have to do it explicitly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,如果您在子表中创建外键,则插入父行时它不会自动填充。如果你想一想,这是有道理的。假设您有一个如下表:
您建议的是,当您向
Students
添加一行时,系统应自动向StudentLoans
添加一行 - 但如果那样呢?学生没有贷款?如果学生确实有贷款,金额应该是多少?系统应该选择一个随机数吗?通常,在这种情况下会发生的情况是您将同时添加学生及其贷款。因此,如果您知道贷款金额和学生姓名,您可以说:
No, if you create a foreign key in a child table, it will not automatically get populated when a parent row gets inserted. If you think about this it makes sense. Let's say you have a table like:
What you are suggesting is that when you add a row to
Students
, the system should automatically add a row toStudentLoans
- but what if that student doesn't have a loan? If the student does have a loan, what should the amount be? Should the system pick a random number?Typically what will happen in this scenario is that you'll be adding a student and their loan at the same time. So if you know the loan amount and the student's name, you can say: