[英]Which foreign key to use in a many-to-one table
Suppose I have a table Books with columns Book_ID (Primary Key), ISBN (Unique), and several others such as Title/author/etc. 假设我有一个表包含Book_ID(主键),ISBN(唯一)和其他几个如Title / author / etc的书籍。
I have another table Sales, with primary key Sale_ID, a foreign key to link to Books, and other fields with info on Sales. 我有另一个表Sales,主键为Sales_ID,链接到Books的外键,以及包含Sales信息的其他字段。 Sales only exist for books with ISBNs.
只有具有ISBN的图书才有销售。 Is it better database design to have Book_ID or ISBN be the primary key.
将Book_ID或ISBN作为主键是更好的数据库设计吗? Note: I will be LEFT JOINing Sales to Books on whichever the foreign key is chosen.
注意:无论选择哪个外键,我都将LEFT JOINING Sales to Books。
UPDATE: Some Books have no ISBN's because they're not published with them. 更新:有些书没有ISBN,因为它们没有与它们一起发布。 However, I don't foresee (at least in the next several years) users being able to sell them, because I have no system for making sure that a given book w/o the ISBN isn't repeated.
但是,我没有预见到(至少在接下来的几年内)用户能够出售它们,因为我没有系统来确保不会重复没有ISBN的给定书籍。
我会一直使用你的主键
In general, I think I would go for the surrogate primary key book_id
as the foreign key. 一般来说,我认为我会将代理主键
book_id
作为外键。
There are a few potential issues that I can identify if you were to use the non-primary key ISBN
as a foreign key: 如果您要将非主键
ISBN
用作外键,我可以识别一些潜在问题:
ISBN
for a particular book. ISBN
。 What would you do in case there is a sale of that book? ISBN
. ISBN
可能不正确。 To edit it, you would have to update all the tables that would be using it as a foreign key. ISBN
in the future. ISBN
书籍。 Why are you storing books without an ISBN
in the first place? ISBN
书籍? book_id
should be much more compact than one on an ISBN
field. book_id
上的索引应该比ISBN
字段上的索引更紧凑。 I would always use ISBN
. 我会一直使用
ISBN
。 This way you have a simple way of enforcing your business rule, "Sales only exist for books with ISBNs" ie by making the ISBN
column NOT NULL
in the Sales
table and referencing the ISBN
column in the Books
table. 通过这种方式,您可以通过一种简单的方式来强制执行业务规则,“仅对具有ISBN的书籍进行销售”,即在“
Sales
表格中将ISBN
列NOT NULL
并引用Books
表格中的ISBN
列。
I don't agree with @Daniel Vassallo that because you might want to start selling books that don't have an ISBN in the future you would want to drop the rule in the database today. 我不同意@Daniel Vassallo,因为你可能想要开始销售未来没有ISBN的书籍,你今天就想把这条规则放到数据库中。 There is a name for this design flaw: future creep.
这个设计缺陷有一个名称:未来的蠕变。 Also, the considerations of 'compact indexes' should always be secondary to those of basic data integrity.
此外,“紧凑索引”的考虑因素应该始终是基本数据完整性的考虑因素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.