简体   繁体   中英

Union of two tables with same columns using sqlalchemy

I'm new to sqlalchemy and am wondering how to do a union of two tables that have the same columns. I'm doing the following:

table1_and_table2 = sql.union_all(self.tables['table1'].alias("table1_subquery").select(),
self.tables['table2'].alias("table2_subquery").select())

I'm seeing this error:

OperationalError: (OperationalError) (1248, 'Every derived table must have its own alias')

(Note that self.tables['table1'] returns a sqlalchemy Table with name table1 .)

Can someone point out the error or suggest a better way to combine the rows from both tables?

First, can you output the SQL generated that creates the problem? You should be able to do this by setting echo=True in your create_engine statement.

Second, and this is just a hunch, try rearranging your subqueries to this:

table1_and_table2 = sql.union_all(self.tables['table1'].select().alias("table1_subquery"),
    self.tables['table2'].select().alias("table2_subquery"))

If my hunch is right it's creating aliases, then running a query and the resulting query results are re-aliased and clashing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM