Union query between multiple tables

11 views
Skip to first unread message

Justvuur

unread,
Jun 2, 2020, 2:09:17 PM6/2/20
to sqlalchemy
Hi All,

I would like to do a union between 3 or 4 tables using the all powerful sqlalchemy. The tables have about 3 columns that are the same but each table has 2 different columns.

Is it possible to do a query as below in sqlalchemy?

Select Col1, Col2, Col3, Col4, Col5 from Table1
Union
Select Col1, Col2, Col3, Null as Col4, Null as Col5 from Table2


Mike Bayer

unread,
Jun 2, 2020, 6:12:19 PM6/2/20
to noreply-spamdigest via sqlalchemy
yes, for example with select():

s1 = select([t.c.c1, t.c.c2, t.c.c3])

s2 = select([t2.c.c1, t.c.c2, null().label('col4'), null.label('col5')])

u1 = union(s1, s2)


I'd recommend using union() and select() to create these queries.  the ORM Query.union() method is not as easy to use and long term the above technique with union() and select() will be how it's done.
--
SQLAlchemy -
The Python SQL Toolkit and Object Relational Mapper
 
 
To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description.
---
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+...@googlegroups.com.

Justvuur

unread,
Jun 5, 2020, 1:09:14 AM6/5/20
to sqlalchemy
Thanks Mike! You are the man!


On Wednesday, 3 June 2020 00:12:19 UTC+2, Mike Bayer wrote:
yes, for example with select():

s1 = select([t.c.c1, t.c.c2, t.c.c3])

s2 = select([t2.c.c1, t.c.c2, null().label('col4'), null.label('col5')])

u1 = union(s1, s2)


I'd recommend using union() and select() to create these queries.  the ORM Query.union() method is not as easy to use and long term the above technique with union() and select() will be how it's done.




On Tue, Jun 2, 2020, at 2:09 PM, Justvuur wrote:
Hi All,

I would like to do a union between 3 or 4 tables using the all powerful sqlalchemy. The tables have about 3 columns that are the same but each table has 2 different columns.

Is it possible to do a query as below in sqlalchemy?

Select Col1, Col2, Col3, Col4, Col5 from Table1
Union
Select Col1, Col2, Col3, Null as Col4, Null as Col5 from Table2



--
SQLAlchemy -
The Python SQL Toolkit and Object Relational Mapper
 
 
To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description.
---
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sqlal...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages