Postgres:SQL列出表外键有没有办法使用SQL列出给定表的所有外键?我知道表名/模式,我可以将其插入。
3 回答
largeQ
TA贡献2039条经验 获得超7个赞
您可以通过information_schema表执行此操作。例如:
SELECT tc.table_schema, tc.constraint_name, tc.table_name, kcu.column_name, ccu.table_schema AS foreign_table_schema, ccu.table_name AS foreign_table_name, ccu.column_name AS foreign_column_name FROM information_schema.table_constraints AS tc JOIN information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schemaWHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='mytable';
呼唤远方
TA贡献1856条经验 获得超11个赞
Ollyc的答案很好,因为它不是Postgres特有的,但是,当外键引用多个列时它会崩溃。以下查询适用于任意数量的列,但它在很大程度上依赖于Postgres扩展:
select att2.attname as "child_column", cl.relname as "parent_table", att.attname as "parent_column", connamefrom (select unnest(con1.conkey) as "parent", unnest(con1.confkey) as "child", con1.confrelid, con1.conrelid, con1.conname from pg_class cl join pg_namespace ns on cl.relnamespace = ns.oid join pg_constraint con1 on con1.conrelid = cl.oid where cl.relname = 'child_table' and ns.nspname = 'child_schema' and con1.contype = 'f' ) con join pg_attribute att on att.attrelid = con.confrelid and att.attnum = con.child join pg_class cl on cl.oid = con.confrelid join pg_attribute att2 on att2.attrelid = con.conrelid and att2.attnum = con.parent
- 3 回答
- 0 关注
- 878 浏览
添加回答
举报
0/150
提交
取消