SQL 创建没有主键的外键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5442785/
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 09:52:53  来源:igfitidea点击:

create foreign key without a primary key

sqlsql-server-2005foreign-keysprimary-keykey

提问by sqlchild

Why is it necessary to have a primary key on a column of one table to which a column of the other table having foreign key references.

为什么需要在一个表的列上有一个主键,而另一个表的列有外键引用。

create table D(Did int)
create table E(Eid int foreign key references D(Did))

The above query gives error:

上面的查询给出了错误:

There are no primary or candidate keys in the referenced table 'D' that match
the referencing column list in the foreign key 'FK__E__Eid__79C80F94'.

采纳答案by gbn

Easy. If you have 2 values the same in the parent table, how do you know which one to associate child rows to? One side of foreign key must be unambiguous

简单。如果父表中有 2 个相同的值,您如何知道将子行关联到哪一个?外键的一侧必须明确

The requirement is also "unique key", not just a primary key which of course unique

要求也是“唯一键”,而不仅仅是主键,当然是唯一的

回答by nvogel

Very good question. There is no fundamental reason why a referential constraint shouldn't reference something other than a candidate key. There is even a name for such constraints: Inclusion Dependencies. A foreign key is just a type of inclusion dependency where the target of the constraint happens to be a candidate key.

很好的问题。引用约束不应该引用候选键以外的其他内容没有根本原因。这种约束甚至有一个名称:包含依赖。外键只是一种包含依赖关系,其中约束的目标恰好是候选键。

Unfortunately SQL doesn't provide good support for inclusion dependencies or even for referential constraints generally. SQL limits its so-called FOREIGN KEY constraints to referencing the columns of a UNIQUE or PRIMARY KEY constraint (not necessarily a candidate key though).

不幸的是,SQL 不能很好地支持包含依赖甚至通常的引用约束。SQL 将其所谓的 FOREIGN KEY 约束限制为引用 UNIQUE 或 PRIMARY KEY 约束的列(尽管不一定是候选键)。

So what you have come up against is really a dubious limitation of SQL. It doesn't mean you are doing anything very wrong.

因此,您遇到的实际上是 SQL 的一个可疑限制。这并不意味着你做错了什么。

回答by danidacar

I thinks the PK it's used internally so the sql server knows on what line to operate on. If you don't have a PK and put the same values on two different rows then the sql server will have trouble processing the commands.

我认为它是在内部使用的 PK,所以 sql server 知道要在哪条线上进行操作。如果您没有 PK 并将相同的值放在两个不同的行上,那么 sql server 将无法处理命令。

回答by froeschli

Without a foreign key on D, records in E have no way of knowing, which record is referenced.

如果 D 上没有外键,E 中的记录就无法知道引用了哪条记录。