我有一个问题:
SELECT
cl.relname AS table_name, a.attname AS column_name,
a.atttypid AS type_name, co.confkey AS keys
FROM
pg_class cl, pg_attribute a, pg_constraint co
WHERE
cl.oid = a.attrelid
AND co.conrelid = cl.oid
AND a.attnum > 0
ORDER BY
column_name
我有一个数据库,里面有很多表,其中一些有外键(据我所知,当表1中的列指向它调用的表2中的另一列时,第一列有一个外键,如我错了请纠正我)。所以我需要显示有关所有表的每一列的一些信息:
我创建了小型数据库并测试了我的查询,结果:
http://s018.radikal.ru/i511/1608/40/80b24b99a969.jpg
如您所见,外键仅适用于House
列,但nope
具有相同的值,我只需要在House
附近标记(来自table2)。
答案 0 :(得分:1)
您遗漏的主要内容是检查a.attnum = ANY(co.conkey)
。但是您还需要考虑其他一些事项:
pg_class
还包含索引,视图,序列和类型pg_constraint
还包含主键,CHECK
约束等。pg_attribute
考虑到所有这些:
SELECT
n.nspname AS schema_name,
cl.relname AS table_name,
a.attname AS column_name,
a.atttypid AS type_name,
co.confkey AS keys
FROM
pg_class cl
JOIN pg_namespace n ON
n.oid = cl.relnamespace
JOIN pg_attribute a ON
a.attrelid = cl.oid
LEFT JOIN pg_constraint co ON
co.contype = 'f' AND
co.conrelid = cl.oid AND
a.attnum = ANY(co.conkey)
WHERE
n.nspname NOT IN ('pg_catalog', 'information_schema') AND
cl.relkind = 'r' AND
a.attnum > 0 AND
NOT a.attisdropped