我的数据库中有两个表。第一个表有第二个表的外键。
我可以通过第一个表的外键获取第二个表名称吗?
regclass
,更简单、更快:
SELECT conrelid::regclass::text AS tbl
, conname AS fk_constraint
, confrelid::regclass::text AS referenced_tbl
FROM pg_constraint
WHERE contype = 'f'
AND conrelid = 'first_table_name'::regclass -- table name
-- AND conname = 'fk_name' -- optionally restrict to given FK
ORDER BY conname;
search_path
。
适用于本世纪的任何版本的 Postgres。
是的,可以。
SELECT ct.oid, conname, condeferrable, condeferred, confupdtype, confdeltype, confmatchtype, conkey, confkey, confrelid, nl.nspname as fknsp, cl.relname as fktab, nr.nspname as refnsp, cr.relname as reftab, description, convalidated
FROM pg_constraint ct
JOIN pg_class cl ON cl.oid=conrelid
JOIN pg_namespace nl ON nl.oid=cl.relnamespace
JOIN pg_class cr ON cr.oid=confrelid
JOIN pg_namespace nr ON nr.oid=cr.relnamespace
LEFT OUTER JOIN pg_description des ON (des.objoid=ct.oid AND des.classoid='pg_constraint'::regclass)
WHERE contype='f' AND ct.conname = 'yourfk_name' -- conrelid = 26941::oid
ORDER BY conname;
只需使用您的外键名称来评估您的fk_name。或者如果愿意的话可以使用 oid。
这适用于 9.3,但我认为 9.x 也适用。