2016-10-13 8 views
1

somethingという列のテーブルがいくつかあります。特定の列を含むすべてのテーブルから行を選択

このような列を持つすべてのテーブルから列somethingのすべての行を選択するにはどうすればよいですか?

1つのクエリで実行できますか?生成されたスクリプトの出力を実行し

SELECT 'SELECT something FROM ' || table_name ||';' 
    FROM information_schema.columns 
    WHERE column_name = 'something' 

:アプローチに

答えて

3

は、動的なスクリプトを作成することです。スキーマ名、カラム型、共用体などが気になる場合は、それに応じて動的SQLの生成を変更してください。

0
begin; 
do $$ 
declare 
    stmt text; 
    tbls text[]; 
    col text := 'x'; 
begin 
    select 
    array_agg(format(
     'select ''%2$s.%3$s'' as tbl, %1$I::text from %2$I.%3$I', 
     col, table_schema, table_name)) 
    into tbls 
    from information_schema.columns 
    where column_name = col; 
    raise info '%', tbls; 
    stmt := array_to_string(tbls, ' union all '); 
    raise info '%', stmt; 
    execute 'declare foo cursor for ' || stmt; 
end $$; 
fetch all from foo; 
rollback; 

と結果(私のテストDB用)です。

INFO: {"select 'public.dummy' as tbl, x::text from public.dummy","select 'nd.t' as tbl, x::text from nd.t"} 
INFO: select 'public.dummy' as tbl, x::text from public.dummy union all select 'nd.t' as tbl, x::text from nd.t 
╔══════════════╤═══╗ 
║  tbl  │ x ║ 
╠══════════════╪═══╣ 
║ public.dummy │ X ║ 
║ nd.t   │ 3 ║ 
╚══════════════╧═══╝ 
(2 rows) 

declare ...文によって作成されたカーソルが唯一のトランザクションに存在するため、それは単一のトランザクション(begin; ... rollback;)で実行する必要があります。

関連する問題