postgresql - 在 Postgis 中,如何从空间表和相关(非空间)表之间的一对多关系构建 Geojson

标签 postgresql postgis

我有一个医院(点)的空间表,它与(非空间)价表(手术、紧急程度等)具有一对多关系

医院(id、姓名、geom); 化合价(ID、名称、化合价)

“name”是公共(public)字段。

如何在 PostgreSQL/Postgis 中构建一个有效的 Geojson,其中每个医院(点)可以有一个或多个价?

我已经尝试过此查询的一些变体,但总是给出相同的错误“用作表达式的子查询返回多个行”。

SELECT row_to_json(fc) FROM 
( 
    SELECT 'FeatureCollection' As type, array_to_json(array_agg(f)) As features from

    (
    SELECT 'Feature' As type, ST_AsGeoJSON(lg.geom)::json As geometry, row_to_json

        ((select l from (select
        v.*
                FROM valence v
                inner join hospital lg  on lg."name" =  v."name" ) As l   
        )) As properties
        from hospital as lg)

     As f 
)  As fc;

非常感谢!

最佳答案

通过此查询,“价”列表将作为属性 properties.valences 中的 json 数组返回

SELECT
  json_build_object(
    'type', 'FeatureCollection',
    'features', json_agg(
      json_build_object(
        'type', 'Feature',
        'geometry', ST_AsGeoJSON(h.geom)::json,
        'properties', json_build_object(
          'name', h.name,
          'valences', (
            -- Generate json array of "valences":
            SELECT array_to_json(array_agg(v.valence)) 
            FROM valence v 
            WHERE v.name = h.name 
            GROUP BY v.name
          )
        )
      ) 
    )
  ) json
FROM
  hospital h

根据 http://geojsonlint.com/ 返回的 GeoJSON 对象有效

关于postgresql - 在 Postgis 中,如何从空间表和相关(非空间)表之间的一对多关系构建 Geojson,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45973454/

相关文章:

ruby - ObjectMapper : Find geo places within a certain square, 按邻近度排序

postgresql - 在 postGIS 中选择特定半径内的查询

node.js - 无法从应用程序容器连接到 postgres DB docker 容器

postgresql - 查询从 postgreSQL 中的连续行查找几何之间的距离

java - 使用 jdbc 时尝试连接到远程 pg db 时出现奇怪的错误

postgresql - pg_restore : [tar archiver] could not find header for file "toc.dat" in tar archive :- [PostgreSQL-11] pg admin 4

postgresql - 唯一约束的排除约束,有区别吗?

postgresql - Sequelize JS : Recursive include same model

leaflet - 如何处理 800k 点作为 MVT

用于地理空间搜索的 MySQL-Solr