I need execute 2 select in SQLAlchemy. For example:
select1 = Session.query(col1, col2, col3, col4).filter(...)
select2 = Session.query(col1, "", "", col4).filter(...)
result = select1.union(select2).all()
The problem is that. I don't know how to write "" value in select2 with SQLAlchemy.
Thanks.
Syntax for Using the SQL UNION OperatorThe number of columns being retrieved by each SELECT command, within the UNION, must be the same. The columns in the same position in each SELECT statement should have similar data types. For example, “char” and “varchar” are identical data types.
UNION or UNION ALL have the same basic requirements of the data being combined: There must be the same number of columns retrieved in each SELECT statement to be combined. The columns retrieved must be in the same order in each SELECT statement.
You probably want some combination of column, literal_column or null, which are in the sqlalchemy.sql module:
>>> print Query((t.c.col1,
... t.c.col2,
... t.c.col3,
... t.c.col4)) \
... .union(
... Query((t.c.col1,
... sqlalchemy.sql.null().label('c2'),
... sqlalchemy.sql.literal_column('""').label('c3'),
... t.c.col2))
... )
SELECT anon_1.table_col1 AS anon_1_table_col1, anon_1.table_col2 AS anon_1_table_col2, anon_1.table_col3 AS anon_1_table_col3, anon_1.table_col4 AS anon_1_table_col4
FROM (SELECT "table".col1 AS table_col1, "table".col2 AS table_col2, "table".col3 AS table_col3, "table".col4 AS table_col4
FROM "table" UNION SELECT "table".col1 AS table_col1, NULL AS c2, "" AS c3, "table".col2 AS table_col2
FROM "table") AS anon_1
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With