简体   繁体   English

主键或唯一列上的 SQL 外键

[英]SQL foreign key on primary key or unique column

Suppose I have two tables, table A and table B, and that table A has the following columns:假设我有两个表,表 A 和表 B,并且表 A 具有以下列:

COLUMNS (id INT PRIMARY KEY, name VARCHAR(200) UNIQUE)

I want to create a column in table B which references a row of table A using a foreign key.我想在表 B 中创建一列,它使用外键引用表 A 的一行。 Most of the time when I look up a row in table BI will also want to retrieve the name field in the row of table A that it references.大多数情况下,当我在表 BI 中查找一行时,还需要检索它引用的表 A 行中的名称字段。 Speed of lookups (but not insertions) is a concern.查找(但不是插入)的速度是一个问题。

Would it be better to use the primary key of table A as the foreign key and then use a JOIN to bring in the value of the name field, or would it be better to use the name field as the foreign key so that that data is already present when looking up a row in table B?是用A表的主键做外键,然后用JOIN把name字段的值带进来,还是用name字段做外键,这样数据就更好了?在表 B 中查找行时已经存在?

Usually the name can change.通常名称可以更改。 Maybe someone finds a better name or there was a typo in the name that must be corrected.也许有人找到了更好的名字,或者名字中有一个必须更正的错字。 Whereas the PK should never change.而PK永远不应该改变。 Always use the ID as FK.始终将 ID 用作 FK。 This is how a lookup table works.这就是查找表的工作方式。

If you use an identity column as PK, the IDs will be generated automatically and cannot be changed.如果您使用标识列作为 PK,则 ID 将自动生成且无法更改。 It is mostly a good idea to have a meaningless PK.进行无意义的PK通常是个好主意。 Meaningful columns tend to be subject of edits.有意义的列往往是编辑的主题。

最好使用表 A 的主键作为外键,然后使用 JOIN 引入 name 字段的值,否则只需将所有内容放在表 B 中

In your example "name" is a nullable column so it is not a candidate key.在您的示例中,“名称”是一个可为空的列,因此它不是候选键。 A foreign key constraint is supposed to reference a candidate key (eg "Id" in this case).外键约束应该引用候选键(例如,在这种情况下为“Id”)。 I recommend you either change the table to make "name" non-nullable or reference Id instead.我建议您更改表以使“名称”不可为空或改为引用 Id。

Nullable UNIQUE and FOREIGN KEY constraints in SQL can be implemented in different ways in different database products. SQL 中可空的 UNIQUE 和 FOREIGN KEY 约束在不同的数据库产品中可以以不同的方式实现。 Their meaning is sometimes ambiguous and the results of using them are often contradictory and probably won't match reality.它们的含义有时是模棱两可的,使用它们的结果往往是矛盾的,可能与现实不符。

(It may be that allowing nulls was just an oversight in your CREATE TABLE statement - in which case I suggest you amend the question). (可能允许空值只是您 CREATE TABLE 语句中的一个疏忽 - 在这种情况下,我建议您修改问题)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM