主键和外键同时存在
在 SQL Server 2008 中是否可以创建一个包含 2 列同时作为主键和外键的表?如果是,这样的代码会是什么样子?我已经搜索过但一无所获。
Would it be possible in SQL Server 2008 to have a table created with 2 columns that are at the same time primary and foreign keys? If yes, how would such a code look like? I've searched and came up with nothing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当然,没问题:
这通常用于建模多对多关系。
Sure, no problem:
This is quite commonly used to model many-to-many relations.
这些是完全不同的结构。
主键用于强制表内的唯一性,并且是特定记录的唯一标识符。
外键用于实现引用完整性,以确保另一个表中存在某个值。
外键需要引用另一个表中的主键。
如果您想要一个唯一的外键,您可以创建一个 FK 约束并向同一字段添加一个唯一索引/约束。
出于参考目的,SQL Server 允许 FK 引用
UNIQUE CONSTRAINT
以及PRIMARY KEY
字段。These are totally different constructs.
A Primary Key is used to enforce uniqueness within a table, and be a unique identifier for a certain record.
A Foreign Key is used for referential integrity, to make sure that a value exists in another table.
The Foreign key needs to reference the primary key in another table.
If you want to have a foreign key that is also unique, you could make a FK constraint and add a unique index/constraint to that same field.
For reference purposes, SQL Server allows a FK to refer to a
UNIQUE CONSTRAINT
as well as to aPRIMARY KEY
field.这可能不是一个好主意,因为您经常希望在表中允许重复的外键。即使你现在不这样做,将来也可能会这样做,所以最好不要这样做。请参阅 将外键作为主键可以吗?
It is probably not a good idea since often you want to allow duplicate foreign keys in the table. Even if you don't now, in the future, you might, so best not to do this. See Is it fine to have foreign key as primary key?
只是一个简短的说明 - 来自 Microsoft 页面 (http://msdn.microsoft.com/ en-us/library/ms189049.aspx)...
“外键约束不必仅链接到另一个表中的主键约束;它还可以定义为引用 UNIQUE 的列约束于另一张桌子。”
不经常使用,但在某些情况下很有用。
Just a quick note - from Microsoft pages (http://msdn.microsoft.com/en-us/library/ms189049.aspx)...
"A foreign key constraint does not have to be linked only to a primary key constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table."
Not used often, but useful in some circumstances.