在python中填充n级PostgreSQL表

问题描述 投票:1回答:1

[我在思考如何填充n级表(在我的情况下为3级)时遇到了麻烦,Im使用python从查询中获取数据,但是我不确定如何填充新表resources,因为它引用自己。对此方法的任何反馈将不胜感激!

在我的python文件中运行以下查询后,得到下表

SELECT distinct c.table_catalog AS "Database", c.table_schema AS "Schema", c.table_name AS "Table"
FROM information_schema.columns c
WHERE c.table_schema != 'information_schema' AND c.table_schema != 'pg_catalog' AND c.table_schema != 'pg_internal' AND c.table_schema not like '% %'
ORDER BY c.table_schema, c.table_name;


Database  Schema            Table
____________________________________
dev       BigBangTheory     SomeTable1
dev       BigBangTheory     SomeTable2
dev       BigBangTheory     SomeTable3
dev       Walle             AnotherTable100
dev       Walle             AnotherTable200
dev       StarWars          SpaceTablexxx
dev       StarWars          SpaceTableyyy
stage     BigBangTheory     SomeTable1
stage     BigBangTheory     SomeTable2
stage     BigBangTheory     SomeTable3
stage     Walle             AnotherTable100
stage     Walle             AnotherTable200
stage     StarWars          SpaceTablexxx
stage     StarWars          SpaceTableyyy

并且我还有另一个要使用以上结果填充的表。我要填充的表如下所示:

CREATE TABLE IF NOT EXISTS resources
(
"id" SERIAL NOT NULL PRIMARY KEY,
"type" varchar(100) NOT NULL,             
"name" varchar(100) NOT NULL,    
"parent" int,
FOREIGN KEY (parent) REFERENCES resources (id)
);

所以我的目标是使表resources看起来像这样:

id      type         name                   parent
____________________________________________________
1       database     dev                    NULL
2       schema       BigBangTheory          1
3       table        SomeTable1             2
4       table        SomeTable2             2
5       table        SomeTable3             2
6       schema       Walle                  1
7       table        AnotherTable100        6
8       table        AnotherTable200        6
9       schema       StarWars               1
10      table        SpaceTablexxx          9
11      table        SpaceTableyyy          9

12      database     stage                  NULL
13      schema       BigBangTheory          12
14      table        SomeTable1             13
15      table        SomeTable2             13
16      table        SomeTable3             13
17      schema       Walle                  12
18      table        AnotherTable100        17
19      table        AnotherTable200        17
20      schema       StarWars               12
21      table        SpaceTablexxx          20
22      table        SpaceTableyyy          20

谢谢你!感谢所有反馈<3

python sql postgresql database-design sql-insert
1个回答
0
投票

首先,您可以直接从information_schema.tables而不是information_schema.columns获得所需的信息(每个表只有一行,因此需要distinct。]]

然后:在Postgres中,您可以通过在Postgres中使用returning子句到insert子句的级联通用表表达式,在单个查询中完成所需的操作。可以

© www.soinside.com 2019 - 2024. All rights reserved.