我记得在播客014中听到Joel Spolsky提到他几乎从未使用过外键(如果我没记错的话)。然而,对我来说,它们对于避免数据库中的重复和后续数据完整性问题非常重要。

人们是否有一些可靠的理由(以避免与Stack Overflow原则一致的讨论)?

编辑:“我还没有创建外键的理由,所以这可能是我真正建立一个外键的第一个理由。”


当前回答

我也听过这种说法——有些人忘记在外键上放索引,然后抱怨某些操作很慢(因为约束检查可以利用任何索引)。所以总结一下:没有好的理由不使用外键。所有现代数据库都支持级联删除,所以…

其他回答

我同意德米特里的回答,说得很好。

For those who are worried about the performance overhead FK's often bring, there's a way (in Oracle) you can get the query optimiser advantage of the FK constraint without the cost overhead of constraint validation during insert, delete or update. That is to create the FK constraint with the attributes RELY DISABLE NOVALIDATE. This means the query optimiser ASSUMES that the constraint has been enforced when building queries, without the database actually enforcing the constraint. You have to be very careful here to take the responsibility when you populate a table with an FK constraint like this to make absolutely sure you don't have data in your FK column(s) that violate the constraint, as if you do so you could get unreliable results from queries that involve the table this FK constraint is on.

我通常在数据集市模式中的某些表上使用这种策略,但在集成登台模式中不使用。我要确保复制数据的表已经强制执行了相同的约束,或者ETL例程强制执行了该约束。

在DB2中,如果使用mqt(物化查询表),优化器需要外键约束才能为任何给定的查询选择正确的计划。由于元数据包含基数信息,优化器会大量使用元数据来决定是否使用MQT。

像许多事情一样,这是一种权衡。这是一个你想在哪里进行验证数据完整性的工作的问题:

(1)使用外键(单点配置为一个表,功能已经实现,经过测试,证明有效)

(2)把它留给数据库的用户(可能多个用户/应用程序更新同一个表),这意味着更多潜在的故障点和测试的复杂性)。

数据库执行(2)更有效,使用(1)更容易维护,风险更小。

在我参与的一个项目中,经常存在隐式关系而不是显式关系,这样可以在同一列上连接多个表。

请看下面的表格

地址

AddressId (PK) EntityId EntityType 城市 状态 国家 等。

EntityType的值可能是Employee、Company、Customer, EntityId指的是您感兴趣的表的主键。

我真的不认为这是最好的方法,但它对这个项目有效。

One time when an FK might cause you a problem is when you have historical data that references the key (in a lookup table) even though you no longer want the key available. Obviously the solution is to design things better up front, but I am thinking of real world situations here where you don't always have control of the full solution. For example: perhaps you have a look up table customer_type that lists different types of customers - lets say you need to remove a certain customer type, but (due to business restraints) aren't able to update the client software, and nobody invisaged this situation when developing the software, the fact that it is a foreign key in some other table may prevent you from removing the row even though you know the historical data that references it is irrelevant. After being burnt with this a few times you probably lean away from db enforcement of relationships. (I'm not saying this is good - just giving a reason why you may decide to avoid FKs and db contraints in general)