将旧表复制到新表,但新表略有不同?
Copying oldtable to newtable with slight differences in newtable?
我有两个表,旧表和新表,
旧表看起来像:
id | type | name
----+------+------
1 | 1 | dog
2 | 2 | bird
3 | 1 | cat
我希望 newtable 有自己的 id 字段,我想插入 oldtable 的所有字段(包括它的 id,根据 type=1 的约束在 newtable 中重命名为 parent_id)。在 postgres 中,我在 newtable 中手动创建了列 "id, parent_id, type, name" 然后做了:
INSERT INTO newtable (id, parent_id, type, name)
SELECT nextval('newtable_id_seq'), id, type, name
FROM oldtable WHERE type=1;
结果(如预期):
id | parent_id | type | name
----+-----------+------+------
1 | 1 | 1 | dog
2 | 3 | 1 | cat
假设我的旧表有多个列并且想要 select 所有与 where 子句相关的记录,我如何在 sqlalchemy 中执行此操作?此外,是否有必要像我在示例中所做的那样,在插入旧表的值之前手动创建希望插入到新表中的每一列?
像这样的东西应该是您要找的东西:
oldTypeOnes = session.query(oldTable).filter(oldTable.type == 1).all()
for oldTypeOne in oldTypeOnes:
session.add(newTable(parent_id=oldTypeOne.id, type=oldTypeOne.type, \
name=oldTypeOne.name))
session.commit()
我有两个表,旧表和新表,
旧表看起来像:
id | type | name
----+------+------
1 | 1 | dog
2 | 2 | bird
3 | 1 | cat
我希望 newtable 有自己的 id 字段,我想插入 oldtable 的所有字段(包括它的 id,根据 type=1 的约束在 newtable 中重命名为 parent_id)。在 postgres 中,我在 newtable 中手动创建了列 "id, parent_id, type, name" 然后做了:
INSERT INTO newtable (id, parent_id, type, name)
SELECT nextval('newtable_id_seq'), id, type, name
FROM oldtable WHERE type=1;
结果(如预期):
id | parent_id | type | name
----+-----------+------+------
1 | 1 | 1 | dog
2 | 3 | 1 | cat
假设我的旧表有多个列并且想要 select 所有与 where 子句相关的记录,我如何在 sqlalchemy 中执行此操作?此外,是否有必要像我在示例中所做的那样,在插入旧表的值之前手动创建希望插入到新表中的每一列?
像这样的东西应该是您要找的东西:
oldTypeOnes = session.query(oldTable).filter(oldTable.type == 1).all()
for oldTypeOne in oldTypeOnes:
session.add(newTable(parent_id=oldTypeOne.id, type=oldTypeOne.type, \
name=oldTypeOne.name))
session.commit()