[英]How to do nested JSON objects in MySQL
I've made two tables for demonstrational purposes;我制作了两张表格用于演示目的;
CREATE TABLE 'owners' (
'id' int PRIMARY KEY AUTO_INCREMENT,
'firstname' varchar(20) NOT NULL,
'lastname' varchar(20) NOT NULL
);
and和
CREATE TABLE 'cars' (
'id' int PRIMARY KEY AUTO_INCREMENT,
'owner_id' int NOT NULL,
'brand' varchar(20),
'model' varchar(20)
);
I want to achieve this JSON:我想实现这个 JSON:
[
{
"brand":"volvo",
"model":"xc90",
"owner":{
"id":"1",
"firstname":"Jon",
"lastname":"Doe"
}
},
{
"brand":"bmw",
"model":"m5",
"owner":{
"id":"1",
"firstname":"Jon",
"lastname":"Doe"
}
},
]
What should my query look like?我的查询应该是什么样的?
I've tried:我试过了:
Join the two tables to relate the cars with their owners.加入这两张表,将汽车与车主联系起来。
Use JSON_OBJECT()
to create the JSON objects, and combine them all into an array with JSON_ARRAYAGG()
.使用JSON_OBJECT()
创建 JSON 对象,并使用 JSON_ARRAYAGG JSON_ARRAYAGG()
) 将它们全部组合成一个数组。
For the nested object, simply use a nested call to JSON_OBJECT()
.对于嵌套对象,只需使用对JSON_OBJECT()
的嵌套调用。
SELECT JSON_ARRAYAGG(
JSON_OBJECT('brand', c.brand, 'model', c.model,
'owner', JSON_OBJECT('id', o.id, 'firstname', o.firstname, 'lastname', o.lastname)
)
)
FROM cars AS c
JOIN owners AS o ON o.id = c.owner_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.