我可以用同一列来表示多个表的外键吗?
我试图使用同一列来表示具有不同列的外键。这是因为可以使用此列对任意数量的表进行索引。
现在,我的想法是使用一个小的 varchar() 字段来表示它们正在索引哪个字段,然后检查它们我可能对所有与给定字段匹配的子查询,然后根据 id 进行查询?
这是利用 MySQL 索引的好方法吗?
还有其他更好的方法来实现这一目标吗?
I am trying to use the same column to represent a has foreign key to different columns. This is because there could be an arbitrary number of tables to be indexed using this column.
Right now, my idea is to use a small varchar() field to represent which field they are indexing and then check for them my probably sub-querying for all that match the given field, then querying based on the id?
Is this a good method that would take advantage of MySQL indexing?
Are there any other better ways to accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我通常使用 Abba 的解决方案来解决一对多关系中的此类问题。使用type字段来定义外键引用的表。
如果这种情况出现在一对一的关系中,您可以考虑扭转这种关系。将外键移至其他表。任意数量的表都可以将外键链接到单个原始表。
I usually use Abba's solution for these sort of problems in a one-to-many relationship. Use a type field to define the table the foreign key reffers to.
If this comes up in a one-to-one relationship you may consider flipping the relationship around. Move the foreign key to the other tables. Any number of tables may link a foreign key to the single original table.
查看 http://github.com/Theaxiom/Polymorphic2.0 多态行为。
您使用 2 个字段来表示与任何其他表的连接。一个字段保存链接模型的 ModelName,另一个字段保存任意任意的foreign_id 值。
Check out the http://github.com/Theaxiom/Polymorphic2.0 Polymorhpic Behavior.
You use 2 fields to represent a connection to any other table. One field holds the ModelName of the linked Model and the other holds any arbitrary foreign_id value.
创建一个“超类型”表来统一其他表中的键。此示例可能会有所帮助:
http: //consultingblogs.emc.com/davidportas/archive/2007/01/08/Distributed-Keys-and-Disjoint-Subtypes.aspx
Create a "supertype" table that unifies the keys from the other tables. This example might help:
http://consultingblogs.emc.com/davidportas/archive/2007/01/08/Distributed-Keys-and-Disjoint-Subtypes.aspx
表示 gen-spec 设计模式的一种方法是使用相同的键作为专用表中的外键和主键。作为外键,它引用通用表中的 PK。通用表中的 PK 引用其中一个专用表中的一行,但不指定是哪一个。
这是在关系模型中对基因规格模式进行建模的常用方法。
One way to represent the gen-spec design pattern is to use the same key as both a foreign key and as a primary key in the specialized tables. As a foreign key, it references the PK in the generalized table. And the PK in the generalized table references a row in one of the specialized tables, without specify which one.
This is the usual method of modeling the gen-spec pattern in the relational model.