SQL Server Management Studio - 添加外键令人困惑?
我总是发现在 Management Studio 中向主表添加外键很令人困惑。
假设我有一个
Table1
{
ID int, -- Primary Key
Table2ID int, -- Refers to Table2's ID
}
Table2
{
ID int, -- Primary Key
SomeData nvarchar(50)
}
我正在通过右键单击 -> 向 Table1 添加外键关系->表和列规范。我将“主”弹出窗口设置为 Table2、ID,将“外键表”设置为 Table1、Table2ID。
我的问题:
不应该列出表2 “外键表”和表1 主键?我的理解是 错误的?
当我保存时,我收到一条警报“下表将保存到您的数据库中。”它显示了两个表。我真的不明白这个。我只改变了表1。为什么显示第二个表?
I always find it confusing to add foreign keys to primary table in Management Studio.
Lets say I have a
Table1
{
ID int, -- Primary Key
Table2ID int, -- Refers to Table2's ID
}
Table2
{
ID int, -- Primary Key
SomeData nvarchar(50)
}
I am adding a foreign key to Table1 by Right Click -> Relationships -> Table and column specification
. I am setting "Primary" popups to Table2, ID and "Foreign Key Table" to Table1, Table2ID.
My questions:
Shouldn't Table2 be listed for
"Foreign Key Table" and Table1 for
Primary Key? Is my understanding
wrong?When I save I get an alert "The following tables will be saved to your database." and it shows both tables. I really don't get this. I only changed Table1. Why is the second table shown?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
为什么不直接使用等效的 T-SQL 语句?对我来说似乎更容易,也更容易混淆:
当我读到这篇文章时,我相信这立即清楚了所涉及的两个表以及它们是如何连接的(
Table1.Table2ID
--(references)--> ;Table2.ID
)如果您想留在 SSMS 设计器世界中:您还可以创建所涉及表的数据库图表,然后只需拖放您的
Table2ID
从Table1
列到Table2
并将其拖放到那里的ID
列 - 这会以图形方式告诉 SSMS 您想要做什么,您只需需要检查您的选择,然后在弹出的对话框中单击“确定”。Why don't you just use the equivalent T-SQL statements?? Seems much easier and less confusing to me:
When I read this, I believe this is immediately clear what two tables are involved, and how they are connected (
Table1.Table2ID
--(references)-->Table2.ID
)If you want to stay in the SSMS designer world: you could also create a database diagram of your tables involved, and then just drag&drop your
Table2ID
column fromTable1
over toTable2
and drop it onto theID
column there - this would graphically tell SSMS what you want to do, and you just need to review your choices and click OK on the dialog that pops up.我相信你的理解是错误的。 Table2 是您正在引用其主键的表。因此它列在主键下。 Table1 是将具有外键(对另一个表的主键的引用)的表;因此它列在“外键表”下。
至于为什么保存两个表,即使后来列出外键属于 Table1:我相信这是因为外键约束了两个表。他们都必须“了解”约束,因此他们都需要被保存。
I believe your understanding is wrong. Table2 is the table whose primary key you are referencing. Therefore it's listed under Primary Key. Table1 is the table that will have the foreign key (the reference to the primary key of another table); therefore it's listed under "Foreign Key Table".
As far as why both tables are saved, even though the foreign key is listed afterward as belonging to Table1: I believe it's because the foreign key constrains both tables. They both have to "know" about the constraint, so they both need to be saved.
按照这种方式在表中创建外键。
Follow this way to create a foreign key in your table.