Home > Database > Mysql Tutorial > How to Generate Nested JSON from Relational Tables in MySQL 5.7?

How to Generate Nested JSON from Relational Tables in MySQL 5.7?

Patricia Arquette
Release: 2024-11-30 20:58:14
Original
570 people have browsed it

How to Generate Nested JSON from Relational Tables in MySQL 5.7?

Generating Nested JSON with MySQL Native Functions

Problem:

Using MySQL 5.7.12's JSON functions, how can you construct a JSON document with embedded sub-objects from data in relational tables?

Database Setup:

Consider the following tables:

CREATE TABLE `parent_table` (
   `id` int(11) NOT NULL,
   `desc` varchar(20) NOT NULL,
   PRIMARY KEY (`id`)
);
CREATE TABLE `child_table` (
   `id` int(11) NOT NULL,
   `parent_id` int(11) NOT NULL,
   `desc` varchar(20) NOT NULL,
   PRIMARY KEY (`id`,`parent_id`)
);
insert `parent_table` values (1,'parent row 1');
insert `child_table` values (1,1,'child row 1');
insert `child_table` values (2,1,'child row 2');
Copy after login

Desired JSON Output:

[{
    "id" : 1,
    "desc" : "parent row 1",
    "child_objects" : [{
            "id" : 1,
            "parent_id" : 1,
            "desc" : "child row 1"
        }, {
            "id" : 2,
            "parent_id" : 1,
            "desc" : "child row 2"
        }
    ]
}]
Copy after login

Solution:

To generate the desired nested JSON, you can use MySQL's GROUP_CONCAT function to concatenate multiple rows from the child_table into a string. Then, wrap the string in a JSON_ARRAY to convert it to a JSON array.

select json_object(
  'id',p.id 
 ,'desc',p.`desc`
 ,'child_objects',(select CAST(CONCAT('[',
                GROUP_CONCAT(
                  JSON_OBJECT(
                    'id',id,'parent_id',parent_id,'desc',`desc`)),
                ']')
         AS JSON) from child_table where parent_id = p.id)

 ) from parent_table p;
Copy after login

This query will generate the JSON document exactly as specified in the desired output.

The above is the detailed content of How to Generate Nested JSON from Relational Tables in MySQL 5.7?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template