Suppose I have a supplier table with supplierID
and another 14 columns. I want to get a list of all tables that any column from supplier is fk there.
I have the following query, it gets all tables which contains FK from supplier.supplierID
:
select (select r.relname from pg_class r where r.oid = c.conrelid) as table,
(select r.relkind from pg_class r where r.oid = c.conrelid) as type,
(select array_agg(attname) from pg_attribute
where attrelid = c.conrelid and ARRAY[attnum] <@ c.conkey) as col,
(select r.relname from pg_class r where r.oid = c.confrelid) as ftable,
(select n.nspname from pg_class r left join pg_namespace n on r.oid=n.oid where r.oid = n.oid) as schema
from pg_constraint c
where c.confrelid = (select oid from pg_class where relname = 'supplier') and
c.confkey @> (select array_agg(attnum) from pg_attribute
where attname = 'supplierID ' and attrelid = c.confrelid);
This is incomplete because I need to know about all columns in supplier, any one of them can be FK somewhere else (lets suppose all columns are unique).
Is there any way to improve my query? I hate to run it 15 items over all columns.