プログラミングで飯を食え。腕をあげたきゃ備忘録!

PHP、JavaScript、HTML5、CSS3などWEB系言語を中心に基本テク、備忘録をまとめます。Android、Iphoneアプリ開発についても!

PostgreSQLで特定の名前のカラムを持つテーブル一覧を取得する方法!

サクウェブTVはコチラ↓↓↓
サクウェブTV

以下のようなSQLを実行します。

SELECT schemas.nspname AS schema_name
     , tables.relname AS table_name
FROM pg_attribute AS colmuns
INNER JOIN pg_class AS tables
  ON colmuns.attrelid = tables.oid
INNER JOIN pg_namespace AS schemas
  ON tables.relnamespace = schemas.oid
WHERE colmuns.attname = 'xxxxxxxxxxxxxxxxxxxxx'
ORDER BY schema_name, table_name

「xxxxxxxxxxxxxxxxxxxxx」の部分に調べたいカラム名を入れます。

SELECT schemas.nspname AS schema_name
     , tables.relname AS table_name
FROM pg_attribute AS colmuns
INNER JOIN pg_class AS tables
  ON colmuns.attrelid = tables.oid
INNER JOIN pg_namespace AS schemas
  ON tables.relnamespace = schemas.oid
WHERE colmuns.attname = 'XXXXXXXXXXXXXXXX'

UNION

SELECT schemas.nspname AS schema_name
     , tables.relname AS table_name
FROM pg_attribute AS colmuns
INNER JOIN pg_class AS tables
  ON colmuns.attrelid = tables.oid
INNER JOIN pg_namespace AS schemas
  ON tables.relnamespace = schemas.oid
WHERE colmuns.attname = 'YYYYYYYYYYYYYYYY'
ORDER BY schema_name, table_name

のようにすれば

XXXXXXXXXXXXXXXX

YYYYYYYYYYYYYYYY

をカラムに持つテーブルを抽出できます。