简体   繁体   English

选择主键和外键

[英]Choosing Primary and Foreign Keys

I am having trouble with the concept of primary and foreign keys.我对主键和外键的概念有疑问。 My guess is that the model will be my primary key?我猜 model 将是我的主键? Not too sure how to connect the rest:/不太确定如何连接 rest:/

Product(maker,model, type)产品(制造商,model,类型)

PC(model, speed, ram, hd, price) PC(型号、速度、内存、高清、价格)

Laptop(model, speed, ram, hd, screen, price)笔记本电脑(型号、速度、内存、高清、屏幕、价格)

Printer(model, color, type, price)打印机(型号、颜色、类型、价格)

Generally you want to have a very static, non repetitive, field as your primary key.通常,您希望有一个非常 static 的非重复字段作为您的主键。 Usually that ends up being an 'id' column with randomly generated non repeating ids (like UUID for example).通常这最终会成为一个“id”列,其中包含随机生成的非重复 id(例如 UUID)。 It's important to keep in mind your primary key is meant to be the identifier for any given row in the table and there for cannot be repeated by any other row on that same table.重要的是要记住,您的主键是表中任何给定行的标识符,并且不能被同一张表上的任何其他行重复。

A foreign key is a value in a column who's source is from another table.外键是列中的值,其来源来自另一个表。 It's hard to give a solid example with the data you've provided since I'm not sure how the tables and their columns are meant to relate with each other, however lets say the Product table's model field is meant to match the model of an item on the PC table.很难用你提供的数据给出一个可靠的例子,因为我不确定表和它们的列是如何相互关联的,但是可以说 Product 表的 model 字段是为了匹配 model电脑桌上的项目。 In this case the model column on Product would have a foreign key relationship to the PC table, meaning that the item stored in the model column on the Product table must match an entry on the PC table, hence the 'foreign' in foreign key.在这种情况下,Product 上的 model 列将与 PC 表有外键关系,这意味着存储在 Product 表上的 model 列中的项目必须与 PC 表上的条目匹配,因此外键中的“外来”。

Generally though you would have the foreign key be a reference to an id rather than an actual field on another table.一般来说,尽管您会让外键成为对 id 的引用,而不是另一个表上的实际字段。 Like perhaps your product table could have a column named something like 'maker_id' and this would have a foreign key relation to the maker_id on a Maker table.就像您的产品表可能有一个名为“maker_id”的列,这将与 Maker 表上的 maker_id 有外键关系。 Then on that Maker table you store several columns with information about that maker.然后在那个 Maker 表上,你存储了几个列,其中包含关于那个制造商的信息。

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

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