首页 > 解决方案 > postgres:使用交叉表或任何 json 函数构建选择查询

问题描述

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 语句的字符串

标签: arraysjsonpostgresqlcrosstabpostgresql-12

解决方案


您可以使用聚合:

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'

DB Fiddle 上的演示

| 问 |
| :---------------------------- |
| 从 public.foo 中选择 i, j |

推荐阅读