SQLAlchemy: Inserting the results of a query into another table
So I have some results which I've got from the install
table, like so:
install = metadata.tables['install']
results = session.query(install) #<sqlalchemy.orm.query.Query object>
I'd like to insert these same results into the install_archive
table.
I'm not entirely sure how to do this, because I don't want to duplicate the schema by defining an install-archive
object and then parsing the results into that. I believe I'm not using the ORM, because I'm just r开发者_C百科eflecting (is that the right term?) the tables and querying them.
All the tutorials I can see use the ORM.
A slow way of doing it, in psudocode, would be:
for id in result.all():
install_archive.insert(install(id))
Thanks in advance!
install_archive \
.insert() \
.from_select(names=['col1', 'col2'], # array of column names that your query returns
select=session.query(install)) # your query or other select() object
This results in (PostgreSQL dialect)
INSERT INTO install_archive (col1, col2)
SELECT install.col1, install.col2
FROM install;
You can do something like this (changing the SELECT
to suit your needs). Just make sure the two tables have the same structure.
INSERT INTO `table1` (SELECT * FROM `table2`);
精彩评论