Sql 从包含特定列的所有表中选择行
我有几个表,其中有一列名为Sql 从包含特定列的所有表中选择行,sql,postgresql,Sql,Postgresql,我有几个表,其中有一列名为something 如何从所有具有此类列的表中选择列某物的所有行 可以在一个查询中完成吗?关于创建动态脚本的方法: SELECT 'SELECT something FROM ' || table_name ||';' FROM information_schema.columns WHERE column_name = 'something' 然后运行生成的脚本的输出。如果您关心架构名称、列类型、联合等,请相应地修改动态sql生成。是的,可以使用联合运算符通
something
如何从所有具有此类列的表中选择列某物的所有行
可以在一个查询中完成吗?关于创建动态脚本的方法:
SELECT 'SELECT something FROM ' || table_name ||';'
FROM information_schema.columns
WHERE column_name = 'something'
然后运行生成的脚本的输出。如果您关心架构名称、列类型、联合等,请相应地修改动态sql生成。是的,可以使用联合运算符通过sql查询完成
我希望有帮助
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;
结果是(对于my test DB):
它应该在单个事务(begin;…rollback;
)中执行,因为由declare…
语句创建的游标只存在于事务中
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;
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)