ANTON KADACH

Generation

text to sql syntaxWed, 18 Jan 2023

The recursive part of the query builds a table r that has all objects at all levels. This is done by iteratively joining the table itself with the geo_objects_attributes and geo_objects tables. The top level region is added in the first part of the union (select 1) and then the geo_objects_attributes and geo_objects tables are joined with the table r itself. This is done for all levels of the hierarchy. In the end, the result is simply joined with the geo_polygons table.

with recursive r as ( select root.id as id, root.name as name, root.level as level, root.parent_id as parent_id, root.id as parent_name, 1 as path_len from geo_objects root where root.parent_id is null union all select a.id as id, a.name as name, a.level as level, a.parent_id as parent_id, r.parent_name as parent_name, path_len + 1 as path_len from geo_objects a join r on a.parent_id = r.id ) select r.id, r.name, r.level, r.parent_id, r.parent_name, r.path_len, g.id as geo_polygon_id, ST_AsGeoJSON(geo_polygon) as geo_polygon from r left outer join geo_polygons g on r.id = g.object_id where r.level = 4 order by r.id;

Questions about programming?Chat with your personal AI assistant