我在PostgreSQL pgAdmin4查询工具中预先指定了geojson作为数据。我正在尝试将数据插入到表中,但由于我的JSON很大,所以不要手动执行Insert,而是执行此操作:
WITH data AS (SELECT '{ "type": "FeatureCollection",
"features": [
{ "type": "Feature",
"geometry": {"type": "Point", "coordinates": [102.0, 0.5]},
"properties": {"prop0": "value0"}
},
{ "type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": [
[102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]
]
},
"properties": {
"prop0": "value0",
"prop1": 0.0
}
}
]
}'::json AS fc)
现在尝试将此数据插入到表格中:
INSERT INTO locations (gid, geom, properties) VALUES ( data );
它给我一个错误column data doesn't exist
。但是当我这样做时:
SELECT
row_number() OVER () AS gid,
ST_AsText(ST_GeomFromGeoJSON(feat->>'geometry')) AS geom,
feat->'properties' AS properties
FROM (
SELECT json_array_elements(fc->'features') AS feat
FROM data
) AS f;
此查询显示数据。我的问题是,当我想要时,我可以选择并查看数据,但因为这不是任何地方的存储所以每次我需要做WITH data as
声明json并应用选择查询。所以我想在我的桌子上插入价值所以我可以随时调用它。
答案 0 :(得分:1)
您应该能够直接使用SELECT
代替VALUES
声明,如下所示:
WITH data AS (SELECT '{ "type": "FeatureCollection",
"features": [
{ "type": "Feature",
"geometry": {"type": "Point", "coordinates": [102.0, 0.5]},
"properties": {"prop0": "value0"}
},
{ "type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": [
[102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]
]
},
"properties": {
"prop0": "value0",
"prop1": 0.0
}
}
]
}'::json AS fc)
INSERT INTO locations (gid, geom, properties)
SELECT
row_number() OVER () AS gid,
ST_AsText(ST_GeomFromGeoJSON(feat->>'geometry')) AS geom,
feat->'properties' AS properties
FROM (
SELECT json_array_elements(fc->'features') AS feat
FROM data
) AS f;