我有一个PostgreSQL函数,可以成功地将其数据作为
返回table(key character varying, value integer)
但是我想返回JSON,因为它更加方便。我已经查看了其他一些答案和文档,但是当使用别名时它会变得复杂(我想将'key'和'value'作为列名返回)。
有人可以推荐表达此功能的最简单,最简洁的方式,不需要额外的复杂性来调用:
DROP FUNCTION get_document_metadata_integer_records_by_document_id(integer);
CREATE OR REPLACE FUNCTION get_document_metadata_integer_records_by_document_id(document_id integer)
RETURNS table(key character varying, value integer) AS
$BODY$
SELECT document_metadata_records.key, document_metadata_integer_records.value FROM document_metadata_integer_records
LEFT OUTER JOIN document_metadata_records
ON document_metadata_integer_records.document_metadata_record_id = document_metadata_records.id
WHERE document_metadata_records.document_id = $1
$BODY$
LANGUAGE sql VOLATILE
COST 100;
ALTER FUNCTION get_document_metadata_integer_records_by_document_id(integer)
OWNER TO postgres;
答案 0 :(得分:1)
使用cross join lateral
作为创建可由row_to_json
create or replace function get_document_metadata_integer_records_by_document_id(
_document_id integer
) returns setof json as $body$
select row_to_json(s)
from
document_metadata_integer_records dmir
left outer join
document_metadata_records dmr on dmir.document_metadata_record_id = dmr.id
cross join lateral
(select dmr.key, dmir.value) s
where dmr.document_id = _document_id
;
$body$ language sql stable;
然后将其用作
select get_document_metadata_integer_records_by_document_id(1) as pair;
或
select pair from get_document_metadata_integer_records_by_document_id(1) j(pair);
或让它返回一个表
) returns table (pair json) as $body$
并用作
select pair from get_document_metadata_integer_records_by_document_id(1);
对于没有lateral
的旧版Postgresql,可以在子查询中执行此操作
select row_to_json(s)
from
(
select dmr.key, dmir.value
from
document_metadata_integer_records dmir
left outer join
document_metadata_records dmr on dmir.document_metadata_record_id = dmr.id
where dmr.document_id = _document_id
) s