外键到多个表中的一个? [英] Foreign key to one of many tables?

查看:161
本文介绍了外键到多个表中的一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设置外键约束的通常方法是选择外键指向哪个表。

The usual way of setting a foreign key constraint is to choose which table the foreign key will point to.

我有一个表与表之间的多态关系,一组表。

I'm having a polymorphic relation between 1 table and a set of table.

这意味着这个表将与集合中的其中一个表有关系。

That means that this table will have a relation with one of those tables in the set.

例如

images: person_id, person_type
subordinates: id, col1, col2...col9
products: id, colA, colB...colZ



在上面的例子中,如果person_type是下级,那么person_id应该是对subordinates.id的外键,并且与产品相同。

In the above example, if person_type is "subordinates" then person_id should be a foreign key to subordinates.id and the same goes with products.

所以我想知道,是否可能有一个外键

So I wonder, is it possible to have a foreign key to one of many tables, or do you have to specifically set which table it points to when you assign one.

这个问题是针对MySQL和PostgreSQL的。

This question is for both MySQL and PostgreSQL.

感谢

推荐答案

不,外键约束总是完全引用一个父表。

No, a foreign key constraint always references exactly one parent table.

这个问题经常出现。以下是我过去的答案:

This question comes up frequently. Here are some of my past answers to it:

  • Why can you not have a foreign key in a polymorphic association?
  • Possible to do a MySQL foreign key to one of two possible tables?
  • Referencing foreign keys in the same column
  • In a StackOverflow clone, what relationship should a Comments table have to Questions and Answers?
  • MySQL - Conditional Foreign Key Constraints
  • How to handle an "OR" relationship in an ERD (table) design?
  • MySQL: Two n:1 relations, but not both at once

有关多态关联的更多信息, =http://www.slideshare.net/billkarwin/practical-object-oriented-models-in-sql =noreferrer> SQL中的实用面向对象模型或我的书, SQL反模式:避免数据库编程的缺陷

For more on Polymorphic Associations, see my presentation Practical Object-Oriented Models in SQL or my book, SQL Antipatterns: Avoiding the Pitfalls of Database Programming.

这篇关于外键到多个表中的一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆