假设我有一个包含supplierID
的供应商表和另外14列。我想获得供应商的任何列都是fk的所有表的列表。
我有以下查询,它从supplier.supplierID
获取包含FK的所有表:
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);
这是不完整的,因为我需要知道供应商中的所有列,其中任何一个都可以是其他地方的FK(假设所有列都是唯一的)。
有没有办法改善我的查询?我讨厌在所有列上运行它15个项目。
答案 0 :(得分:1)
您可以查看以下查询,看看它是否提供了所需的结果
SELECT mytable.table_name AS mytablename, kcu.column_name AS mycolumns, allforeignkey.table_name AS referredtable, allforeignkey.column_name AS referredcolumn
FROM information_schema.table_constraints AS mytable
JOIN (
SELECT table_name,column_name,unique_constraint_name FROM information_schema.referential_constraints
INNER JOIN information_schema.key_column_usage AS kcu ON information_schema.referential_constraints.constraint_name = kcu.constraint_name
) AS allforeignkey ON mytable.constraint_name = allforeignkey.unique_constraint_name
INNER JOIN information_schema.key_column_usage AS kcu ON mytable.constraint_name = kcu.constraint_name
WHERE mytable.constraint_type = 'UNIQUE' AND mytable.table_name = 'your_table_name';
基本上我正在做的是我获取了指定表的所有UNIQUE
列,然后是数据库中所有外键的列表并加入结果,这将给出UNIQUE
列已在其他表格中引用