用json字段按键连接元素
CREATE TABLE customer_json (
ID serial NOT NULL PRIMARY KEY,
info json NOT NULL
);
INSERT INTO customer_json (info) VALUES ('{ "customer": ["John Doe"]}');
INSERT INTO customer_json (info) VALUES ('{ "customer": ["Peter Doe"]}');
INSERT INTO customer_json (info) VALUES ('{ "customer": ["Welsey Doe"]}');
select json_agg(info) from customer_json
结果:
[
{ "customer": ["John Doe"]},
{ "customer": ["Peter Doe"]},
{ "customer": ["Welsey Doe"]}
]
通缉:
[
{ "customer": [
"John Doe",
"Peter Doe",
"Welsey Doe"
]
}
]
发布于 2019-08-27 08:16:01
SELECT
json_agg(object)
FROM (
SELECT
json_build_object(
'customer',
json_agg(info -> 'customer' -> 0)
) as object
FROM
customer_json
) s
info -> 'customer' -> 0
获取名称(首先获取customer
的值JSON数组,然后获取它们的第一个值)json_agg()
将它们聚合到一个JSON数组中json_agg()
作为第二个组使用。或者,您可以在特殊情况下使用json_build_array()代替步骤4:
SELECT
json_build_array(
json_build_object(
'customer',
json_agg(info -> 'customer' -> 0)
)
)
FROM
customer_json
https://stackoverflow.com/questions/57678389
复制