简体   繁体   中英

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:

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. 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. 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?

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. Always use the ID as 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. It is mostly a good idea to have a meaningless 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). I recommend you either change the table to make "name" non-nullable or reference Id instead.

Nullable UNIQUE and FOREIGN KEY constraints in SQL can be implemented in different ways in different database products. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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