Yes, we can.
Have a look at the following example (especially the correlate
method call):
from sqlalchemy import select, func, table, Column, Integer
table1 = table('table1', Column('col', Integer))
table2 = table('table2', Column('col', Integer))
subquery = select(
[func.if_(table1.c.col == 1, table2.c.col, None)]
).correlate(table1)
query = (
select([table1.c.col,
subquery.label('subquery')])
.select_from(table1)
)
if __name__ == '__main__':
print(query)
will result in the following query
SELECT table1.col, (SELECT if(table1.col = :col_1, table2.col, NULL) AS if_1
FROM table2) AS subquery
FROM table1
As you can see, if you call correlate
on a select
, the given Table
will not be added to it's FROM
-clause.
You have to do this even when you specify select_from
directly, as SQLAlchemy will happily add any table it finds in the columns.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…