PostgreSQL中的动态选择列
我想从表中选择一列,列名是如下查询的结果:PostgreSQL中的动态选择列,postgresql,dynamic,Postgresql,Dynamic,我想从表中选择一列,列名是如下查询的结果: -- This query returns a single value with x as ( select a from table1 where <condition> ) -- my_function() yields a table select x from my_function() 我该怎么做 非常感谢。您可以使用SQL编写它,其中包含一个临时函数: CREATE FUNCTION pg_temp.tablefu
-- This query returns a single value
with x as (
select a from table1 where <condition>
)
-- my_function() yields a table
select x from my_function()
我该怎么做
非常感谢。您可以使用SQL编写它,其中包含一个临时函数:
CREATE FUNCTION pg_temp.tablefunc()
RETURNS SETOF my_function_result_type
LANGUAGE plpgsql AS
$$DECLARE
v_colname text;
BEGIN
SELECT a INTO v_colname
FROM table1
LIMIT 1;
RETURN QUERY EXECUTE
format(E'SELECT %I\n'
'FROM my_function()',
v_colname);
END;$$;
SELECT * FROM pg_temp.tablefunc();
您必须编写两个查询,其中第二个查询是根据第一个查询的结果构造的。您可以在客户机代码中或在数据库中执行此操作,例如在do语句中使用PL/pgSQL。你能提供一个更明确的解决方案吗?谢谢