0
我想從嵌套字典結構輸入數據到PostgreSQL數據庫使用psycopg2如here所示。我不確定的是如何訪問字典的嵌套部分,或者甚至可以在一個插入查詢中執行。數據結構是這樣的:巢詞典插入到psycopg2
dictionary = ({
"article_id":94527, "article_title":"An article title",
"country_info": [{"country_id":281133,
"country_code":"GB",
"country_name":"United Kingdom",
"lon":32.0000,
"lat":49.0000},
{"country_id":281133,
"country_code":"FR",
"country_name":"France",
"lon":22.0000,
"lat":39.0000}]
})
和查詢到目前爲止是這樣的:
cur.execute("""
WITH article_s AS (
SELECT id FROM article
WHERE id = %(article_id)s
),
article_i AS (
INSERT INTO article (article_id, article_title)
SELECT %(article_id)s, %(article_title)s
WHERE NOT EXISTS (SELECT id FROM article where id = %(article_id)s)
RETURNING id
),
country_s AS (
SELECT id FROM country
WHERE id = %(country_id)s
),
country_i AS (
INSERT INTO country (id, country_code, country, geom)
SELECT %(country_id)s, %(country_code)s, %(country_name)s, ST_SetSRID(ST_MakePoint(%(lon)s, %(lat)s), 4326)
WHERE NOT EXISTS (SELECT 1 FROM country_s)
RETURNING id
)
INSERT INTO article_countries (article_id, country_id)
SELECT COALESCE (article_i.id, country_i.id),
COALESCE (article_i.id, country_i.id)
FROM article_i, country_i,
article_s, country_s
;
""", dictionary)
人對如何實現這一目標有什麼建議?提前致謝!
謝謝肯定看起來很有希望,但仍然沒有得到解決嵌套數據到查詢的問題。你能舉個例子嗎? – sammy88888888