postgres:使用交叉表或任何json函数构建选择查询

问题描述 投票:0回答:1
create table foo (i int, j text);

select table_schema, table_name, column_name , ordinal_position 
from information_schema.columns where table_name = 'foo';

Output

table_schema   table_name  column_name  ordinal_position
public         foo             i             1 
public         foo             j             2

通过使用第二条语句,我需要形成一个选择查询select i, j from public.foo。一个简单的函数就足够了,如果我们传递表名,则结果可以是select语句的字符串

arrays json postgresql crosstab postgresql-12
1个回答
0
投票

您可以使用聚合:

select concat_ws(' ',
    'select',
    string_agg(column_name, ', ' order by ordinal_position),
    'from',
    table_schema || '.' || table_name
) q
from information_schema.columns 
where table_name = 'foo'
group by table_schema, table_name

或不带group by子句:

select concat_ws(' ',
    'select',
    string_agg(column_name, ', ' order by ordinal_position),
    'from',
    max(table_schema) || '.' || max(table_name)
) q
from information_schema.columns 
where table_name = 'foo' and table_schema = 'public'

Demo on DB Fiddle

| q || :-------------------------- ||从public.foo中选择i,j |
© www.soinside.com 2019 - 2024. All rights reserved.