Sql 如何在循环查询中将结果作为JSON返回?
我循环并从多个表中获取结果,并形成一个结果。我怎样才能得到结果?我现在所做的就是记录它。另外,当我使用array_append时,它将json转换为字符串 这是我正在运行以获取数据的代码Sql 如何在循环查询中将结果作为JSON返回?,sql,postgresql,Sql,Postgresql,我循环并从多个表中获取结果,并形成一个结果。我怎样才能得到结果?我现在所做的就是记录它。另外,当我使用array_append时,它将json转换为字符串 这是我正在运行以获取数据的代码 do $$ DECLARE sampleproductId varchar; productIds text[] := array [ 'abc1', 'abc2' ];
do
$$
DECLARE
sampleproductId varchar;
productIds text[] := array [
'abc1',
'abc2'
];
tId varchar;
DECLARE result jsonb;
DECLARE resultS jsonb[];
begin
FOREACH sampleproductId IN ARRAY productIds
LOOP
tId := (select id
from product.product
where uid = sampleproductId);
result = (select row_to_json(row)
from (select accountid as "accountid", tId as "productUID", sampleproductId as "sampleproductId"
from product.accountproductmap
where productId = cast(tId as int)) row);
if (result is not null) then
resultS = array_append(resultS, result);
end if;
END LOOP;
RAISE NOTICE 'Result: %', resultS;
end ;
$$;
我得到的结果是
{"{\"accountid\": 8133, \"productUID\": \"1685\", \"sampleproductId\": \"abc1\"}","{\"accountid\": 9034, \"productUID\": \"2114\", \"sampleproductId\": \"abc2\"}"}
我不知道为什么array_append会在添加它之前将其转换为字符串,而不仅仅是将其保留为json
我想把它格式化成这样
[
{ "accountid": 8133, "productUID": 1685, "sampleproductId": "abc1" },
{ "accountid": 9034, "productUID": 2114, "sampleproductId": "abc2" }
]
您可以使用普通SQL实现这一点,因为 在函数的帮助下,数组很容易转换为表格结果。所以,您可以将输入输入输入到查询中。 SQL的开发目的是以声明的方式有效地处理集合,而不是通过简单的循环。这就是为什么你应该使用连接而不是循环。 要序列化json中的数据,可以使用jsonb_agg。因此,这是一个查询:
dbfiddle用于使用普通SQL完成此操作。另外,请描述一下,将其转换为字符串并保留为json是什么意思。JSON是人类可读的,所以我认为JSON和适当格式的一些文本输出没有区别format@astentx谢谢我添加了预期的响应。@astentx我以前从未使用过unnest。我应该在哪里使用它?我刚刚尝试了从unestresults中选择*,但没有成功。
create table product
as
select *
from (
values
(1, 'abc1'),
(2, 'abc2'),
(3, 'def1'),
(4, 'def2')
) as t (id, uid)
create table accountproductmap
as
select *
from (values
(1, 123),
(2, 456),
(3, 789)
) as t(productid, accountid)
with sp as (
select *
from unnest('{
abc1,
abc2,
abc\,3
}'::varchar(10)[]
) sampleproductid
)
select jsonb_agg(
jsonb_build_object(
'accountid', a.accountid,
'productUID', p.id,
'sampleproductId', p.uid
)) as q
from sp
join product as p
on sp.sampleproductid = p.uid
join accountproductmap as a
on p.id = a.productid
| q |
| :------------------------------------------------------------------------------------------------------------------------------- |
| [{"accountid": 123, "productUID": 1, "sampleproductId": "abc1"}, {"accountid": 456, "productUID": 2, "sampleproductId": "abc2"}] |