3

鉴于此查询:-

SELECT id as id,
       attributes->>'name' as file_name, 
       status 
from workflow.events 
where schema='customer' 
  and type='FILE_UPLOAD'

id,file_name, status
1,name,status
2,name2,status2

我想输出这个结构:-

{
 "1" :{"id" :"1", "file_name" : "name", "status" : "status1"},
 "2" :{"id" :"2", "file_name" : "name2","status" : "status2"}
}

我现在可以使用字符串函数来做到这一点,但这似乎很混乱且效率低下。可以使用本机 postgresql json 函数来完成吗?

4

1 回答 1

4

如果要使用 json 获取两条记录,请使用row_to_json()函数:

with cte as (
    select 
        id as id,
        attributes->>'name' as file_name, 
        status 
     from workflow.events 
     where schema='customer' and type='FILE_UPLOAD'
)
select row_to_json(c) from cte as c

输出:

{"id":1,"file_name":"name","status":"status"}
{"id":2,"file_name":"name2","status":"status2"}

如果要获取 json 数组:

with cte as (
    select 
        id as id,
        attributes->>'name' as file_name, 
        status 
     from workflow.events 
     where schema='customer' and type='FILE_UPLOAD'
)
select json_agg(c) from cte as c

输出:

[{"id":1,"file_name":"name","status":"status"}, 
 {"id":2,"file_name":"name2","status":"status2"}]

但是对于你想要的输出,我只能建议字符串转换:

with cte as (
    select 
        id::text as id,
        file_name, 
        status 
    from workflow.events 
    where schema='customer' and type='FILE_UPLOAD'
)
select ('{' || string_agg('"' || id || '":' || row_to_json(c), ',') || '}')::json from cte as c

sql fiddle demo

于 2013-10-15T13:51:31.547 回答