如何解决如何通过SQL PL / JSON生成JSON
我正在尝试使用PL / JSON从SQL生成JSON
declare
customer json_list := json_list();
product json_list;
begin
customer:= json_dyn.executeList('SELECT DISTINCT
A.customer_id,A.customer_name,FROM customer A
WHERE A.customer_id = 1');
product := json_dyn.executeList('SELECT DISTINCT
A.product_id,A.product_name,FROM sales A
INNER JOIN customer B
ON A.customer_id = B.customer_id
WHERE A.customer_id = 1');
end;
我需要将这两个选择合并为一个JSON,如下所示: 在某种程度上,产品是销售的关键,产品的价值是产品的列表
[
{
"customer_id": 1,"customer_name": "Customer A","product": [
{
"product_id": 5715,"product_name": "Product A",},{
"product_id": 7841,"product_name": "Product B",}
]
}
]
有人知道怎么做吗?
解决方法
declare
v_customers pljson_list := pljson_list();
v_customer pljson;
v_products pljson_list;
begin
for c in (select distinct customer_id,customer_name
from customer
where customer_id = 1) loop
v_customer := pljson();
v_customer.put('customer_id',c.customer_id);
v_customer.put('customer_name',c.customer_name);
v_products := json_dyn.executeList('select distinct product_id,product_name
from sales
where customer_id = ' || c.customer_id);
v_customer.put('products',v_products.to_json_value);
v_customers.append(v_customer.to_json_value);
end loop;
end;
在此代码段中,我使用了pljson类型(最新版本为https://github.com/pljson/pljson):如果您使用的是旧版本的库,则用“ json”替换任何出现的“ pljson”应该就足够了(但是我建议升级,否则您在Oracle 18或更高版本上可能会遇到问题。
,我想“列表”来自某个表:
declare
v_customers pljson_list := pljson_list();
v_products pljson_list;
v_lists pljson_list;
v_customer pljson;
v_product pljson;
begin
for c in (select distinct customer_id,c.customer_name);
v_products := pljson_list();
for p in (select distinct product_id,product_name
from sales
where customer_id = c.customer_id) loop
v_product := pljson();
v_product.put('product_id',p.product_id);
v_product.put('product_name',p.product_name);
v_lists := json_dyn.executeList('select distinct a,b
from lists
where product_id = ' || p.product_id);
v_product.put('list',v_lists.to_json_value);
v_products.append(v_product.to_json_value);
end loop;
v_customer.put('products',v_products.to_json_value);
v_customers.append(v_customer.to_json_value);
end loop;
end;
HTH。
,@archimede,就是列表中的一个列表
{
"customer_id": 1,"customer_name": "Customer A","product": [
{
"product_id": 5715,"product_name": "Product A","list" : [
{
"a" : 1,"b": 2
},{
"a" : 10,"b" : 20
}
]
}
]
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。