简体   繁体   English

PostgreSQL函数:将多行返回为JSON

[英]PostgreSQL Function: Return Multiple Rows as JSON

I have a PostgreSQL function which successfully returns its data as 我有一个PostgreSQL函数,该函数成功返回其数据为

table(key character varying, value integer)

but I want to return JSON as it's more convenitent. 但我想返回JSON,因为它更方便。 I have looked at some other answers, and documentation, but it gets complicated when aliases are used (I'd like to return 'key' and 'value' as the column names). 我看过其他一些答案和文档,但是使用别名时,情况变得很复杂(我想返回“键”和“值”作为列名)。

Can someone please recommend the most simple and concise way of expressing this function, in a way that does not require extra complexity to call: 有人可以推荐一种表达此功能的最简单明了的方法,而无需额外的复杂性来调用:

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;

Use cross join lateral as a clean and easy path to create a composite type that can be used by row_to_json 使用cross join lateral row_to_json作为干净简单的路径来创建可由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;

then use it as 然后将其用作

select get_document_metadata_integer_records_by_document_id(1) as pair;

or 要么

select pair from get_document_metadata_integer_records_by_document_id(1) j(pair);

or make it return a table 或使其返回表

) returns table (pair json) as $body$

and use as 并用作

select pair from get_document_metadata_integer_records_by_document_id(1);

With older versions of Postgresql without lateral it is possible to do it in a subquery 使用没有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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM