Suppose I have following tables in PostgreSQL database:
base_rel (id SERIAL, ...)
sub_rel (id SERIAL, base_id INT)
sub_sub_rel (id SERIAL, sub_id INT)
I need a to lookup all inheritance path in one query (lookup base_rel.id and sub_rel.id assuming that I know sub_sub_rel.id). The naive way does not work, because you cannot use computed values as argument to subqueries. So following example code fails:
SELECT
(SELECT sub_id FROM sub_sub_rel WHERE id = X) AS sub_id,
(SELECT base_id FROM sub_rel WHERE id = sub_id) AS base_id;
But I need to know these IDs in one query. There is relatively big inheritance tree, so I cannot create PL/pgSQL function for each table, but I can build queries dynamically. Is there a way to fetch these IDs?
As of recursive tables with self-referrental columns — these entities are totally different, for example 'User extends Group extends Server default'.
P.S.: A reason to have these IDs in one query is inheritance table with data like this:
entity_type | entity_id | priority | value
-------------|-----------|----------|-------
1 | 2 | 10 | xxx
2 | 20 | 20 | yyy
3 | 10 | 30 | zzz
Of course, I can build these IDs (10 of sub_sub_rel -> 20 of sub_rel -> 2 of base_rel) on application side and the fetch value with highest priority, but it will require N database round-trips because each ID depends on previous. So I seek a method to do this in one round-trip.