Possible to do a MySQL foreign key to one of two possible tables?

后端 未结 5 1146
渐次进展
渐次进展 2020-11-22 06:11

Well here\'s my problem I have three tables; regions, countries, states. Countries can be inside of regions, states can be inside of regions. Regions are the top of the fo

5条回答
  •  爱一瞬间的悲伤
    2020-11-22 06:28

    This isn't the most elegant solution in the world, but you could use concrete table inheritance to make this work.

    Conceptually you are proposing a notion of a class of "things that can be popular areas" from which your three types of places inherit. You could represent this as a table called, for example, places where each row has a one-to-one relationship with a row in regions, countries, or states. (Attributes that are shared between regions, countries, or states, if any, could be pushed into this places table.) Your popular_place_id would then be a foreign key reference to a row in the places table which would then lead you to a region, country, or state.

    The solution you propose with a second column to describe the type of association happens to be how Rails handles polymorphic associations, but I'm not a fan of that in general. Bill explains in excellent detail why polymorphic associations are not your friends.

提交回复
热议问题