I’m working with a database table that has a hierarchical structure where records reference their parent records. My goal is to create a single nested JSON output using MariaDB 11.4. I’m not experienced with recursive CTEs and need help building a query that can transform my flat table data into a properly nested JSON structure.
Here’s an example of what I want to achieve:
{
"org_id": 1,
"department_name": "headquarters",
"has_subdepts": 1,
"subdepartments": [
{
"org_id": 2,
"department_name": "operations",
"has_subdepts": 1,
"subdepartments": [
{
"org_id": 3,
"department_name": "production",
"has_subdepts": 0,
"subdepartments": []
},
{
"org_id": 4,
"department_name": "quality_control",
"has_subdepts": 0,
"subdepartments": []
}
]
},
{
"org_id": 5,
"department_name": "administration",
"has_subdepts": 1,
"subdepartments": [
{
"org_id": 6,
"department_name": "human_resources",
"has_subdepts": 0,
"subdepartments": []
}
]
}
]
}
I need a recursive CTE approach that can handle multiple levels of nesting and output everything as one JSON object.