I use Oracle 11g and have a massive number of tables representing inheritance, where a base parent table has a primary key NUMBER ID
. The subsequent tables inherit from it, representing through the shared primary key NUMBER ID
. Let's assume there is a multiple layers of such inheritance.
To have a clear picture, let's work with the following simplified structure and assume the hierarchy is quite complex:
- TABLE FOOD
- TABLE FRUIT
- TABLE CYTRUS
- TABLE ORANGE
- TABLE GREPFRUIT
- TABLE VEGETABLE
- TABLE MEAT
- TABLE BEEF
- TABLE SIRLOIN
- TABLE RIB EYE
- TABLE CHICKEN
This is not taxative, regardless of how dumb the example is, assume such a multi-layered hierarchy using Class Table Inheritance (aka Table Per Type Inheritance).
If you want to insert a record to a table ORANGE
having a certain generated ID
, there must be inserted records to the parent tables (CYTRUS
, FRUIT
and FOOD
) as well. Assume an ORM engine takes care after this as keeping such consistency would be very complex.
Let's also assume each of the tables in the hierarchy ends with a certain word (let's say FOOD
: FRUIT_FOOD
, CYTRUS_FOOD
etc.) - I didn't include it to the chart above for sake of clarity.
Question: I have found a record in FOOD
table with ID = 123
based on certain criteria. Thanks to the hierarchical structure, how do I find what tables contain the record with the very same ID using SQL only? I.e. my goal is to find out what * the lowest type in the hierarchy* the certain ID
is related to.
Note: If you have also an answer for a newer version of Oracle, don't hesitate to include it as long as others might find it useful.