pg_constraint で外部キー情報取得

2017/08/30

pg_constraint の内部キー、外部キーは、pg_class、pg_attribute にアクセスしないと取得できない。

・contype = 'f' ・conrelid(内部テーブル):smallint ・confrelid(外部テーブル):smallint ・conkey(内部キー): smallint[] ・confkey(外部キー): smallint[]

まず、内部キーテーブルを作成して、副問い合わせで外部キーも連結させる。 内部キー、内部キーは数値配列なので抽出に「ANY」を利用する。

[sql] SELECT origin.*, pg_class.oid as foreign_class_id, pg_class.relname as foreign_relname, pg_attribute.attnum as foreign_attnum, pg_attribute.attname as foreign_attname FROM ( SELECT pg_constraint.conrelid , pg_class.oid as pg_class_id , pg_class.relname , pg_attribute.attnum , pg_attribute.attname , pg_constraint.confrelid , pg_constraint.confkey , pg_constraint.contype FROM pg_constraint LEFT JOIN pg_attribute ON pg_constraint.conrelid = pg_attribute.attrelid AND pg_attribute.attnum = ANY(pg_constraint.conkey) LEFT JOIN pg_class ON pg_constraint.conrelid = pg_class.oid WHERE pg_constraint.contype = 'f' AND pg_constraint.conrelid = 'pg_classのID' ) AS origin LEFT JOIN pg_attribute ON origin.confrelid = pg_attribute.attrelid AND pg_attribute.attnum = ANY(origin.confkey) LEFT JOIN pg_class ON origin.confrelid = pg_class.oid ; [/sql]