SQL 我们可以有一个不是任何其他表中的主键的外键吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2895219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 06:19:20  来源:igfitidea点击:

can we have a foreign key which is not a primary key in any other table?

sqlsql-serverdatabase-designforeign-keys

提问by Mac

it is written in every book that foreign keys are actually primary key in some other table but can we have a foreign key which is not primary key in any other table

每本书都写外键实际上是其他表中的主键,但是我们可以有一个不是任何其他表中的主键的外键吗

回答by marc_s

Yes - you can have a foreign key that references a unique index in another table.

是的 - 您可以有一个引用另一个表中唯一索引的外键。

CREATE UNIQUE INDEX UX01_YourTable ON dbo.YourTable(SomeUniqueColumn)

ALTER TABLE dbo.YourChildTable
   ADD CONSTRAINT FK_ChildTable_Table
   FOREIGN KEY(YourFKColumn) REFERENCES dbo.YourTable(SomeUniqueColumn)

回答by nvogel

By definition a foreign key must reference a candidate key of some table. It doesn't necessarily have to be the primary key.

根据定义,外键必须引用某个表的候选键。它不一定是主键。

As a matter of detail the constraint called a FOREIGN KEY in SQL isn't exactly equivalent to the textbook definition of a foreign key in the relational model. SQL's FOREIGN KEY constraint differs because:

作为细节问题,SQL 中称为 FOREIGN KEY 的约束并不完全等同于关系模型中外键的​​教科书定义。SQL 的 FOREIGN KEY 约束不同,因为:

  • it can reference any set of columns subject to a uniqueness constraint even if they are not candidate keys (superkeys or nullable columns for example).
  • it may include nulls, in which case the constraint is not enforced
  • its syntax depends on column order, so a fk constraint on (A,B) referencing (A,B) is different to a constraint on (B,A) referencing (A,B).
  • 它可以引用受唯一性约束的任何列集,即使它们不是候选键(例如超级键或可为空的列)。
  • 它可能包含空值,在这种情况下不强制执行约束
  • 它的语法取决于列顺序,因此 (A,B) 引用 (A,B) 上的 fk 约束不同于 (B,A) 引用 (A,B) 上的约束。

回答by Giriraj Gupta

Yes , There can be a foreign key which is unique key in other table as Unique key is subset of primary key but not the exact primary key.

是的,可以有一个外键,它是其他表中的唯一键,因为唯一键是主键的子集,但不是确切的主键。

So that's possible that foreign key is unique key in aother table.

所以外键可能是另一个表中的唯一键。

回答by Riaj Ferdous

General standard answer is no. It is only possible if foreign key refers any column uniquely in other table. That means foreign key must be the candidate key in other table and primary key is also a candidate key the table.

一般标准答案是否定的。仅当外键唯一地引用其他表中的任何列时才有可能。这意味着外键必须是其他表中的候选键,主键也是该表的候选键。