How do you deal with polymorphism in a database?

后端 未结 13 1077
小蘑菇
小蘑菇 2020-11-28 02:11

Example

I have Person, SpecialPerson, and User. Person and SpecialPerson are just people - they don\

相关标签:
13条回答
  • 2020-11-28 03:03

    At the risk of being an 'architecture astronaut' here, I would be more inclined to go with separate tables for the subclasses. Have the primary key of the subclass tables also be a foreign key linking back to the supertype.

    The main reason for doing it this way is that it then becomes much more logically consistent and you do not end up with a lot of fields that are NULL and nonsensical for that particular record. This method also makes it much more easy to add extra fields to the subtypes as you iterate your design process.

    This does add the downside of adding JOINs to your queries, which can impact performance, but I almost always go with an ideal design first, and then look to optimise later if it proves to be necessary. The few times I have gone the 'optimal' way first I have almost always regretted it later.

    So my design would be something like

    PERSON (personid, name, address, phone, ...)

    SPECIALPERSON (personid REFERENCES PERSON(personid), extra fields...)

    USER (personid REFERENCES PERSON(personid), username, encryptedpassword, extra fields...)

    You could also create VIEWs later on that aggregates the supertype and the subtype, if that is necessary.

    The one flaw in this approach is if you find yourself heavily searching for the subtypes associated with a particulare supertype. There is no easy answer to this off the top of my head, you could track it programmatically if necessary, or else run soem global queries and cache the results. It will really depend on the application.

    0 讨论(0)
提交回复
热议问题