Skip to content

Instantly share code, notes, and snippets.

@GastonZalba
Last active August 13, 2020 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GastonZalba/788bffe5f176aa9f00bd84a83c761304 to your computer and use it in GitHub Desktop.
Save GastonZalba/788bffe5f176aa9f00bd84a83c761304 to your computer and use it in GitHub Desktop.
Create a geojson from mutiples tables in PostrgreSQL and PostGIS
SELECT json_build_object(
'type', 'FeatureCollection',
'crs', json_build_object(
'type', 'name',
'properties', json_build_object(
'name', 'EPSG:4326'
)
),
'features', json_agg(ST_AsGeoJSON(t.*)::json)
)
FROM (
SELECT
/* Accept multiples fields */
ta1.name,
ta1.geom
FROM
table1 ta1
WHERE
ta1.id = $1
UNION ALL
SELECT
Null, /* Null value is accepted */
ta2.geom
FROM
table2 ta2
WHERE
ta2.id = $1
UNION ALL
SELECT
ta3.name_in_other_column, /* The columns names doesn't have to match */
ta3.geom
FROM
table3 ta3
WHERE
ta3.id = $1
) as t(name, geom);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment