SQLAlchemy中的依赖CTE? (里面的例子)

时间:2015-11-19 10:04:07

标签: python postgresql sqlalchemy flask-sqlalchemy

这是PostgreSQL中一个非常简单的例子:

WITH a AS (
    SELECT 1 AS x
),   b AS ( 
    SELECT x AS y
    FROM a
)
SELECT y
FROM b;

如何让SQLAlchemy生成它(最好使用声明式)?

1 个答案:

答案 0 :(得分:0)

这有效:

from sqlalchemy import literal

a = session.query(literal(1).label('x')).cte('a')
b = session.query(a.c.x.label('y')).cte('b')
res = session.query(b).all()

assert res[0].y == 1

相关文档:http://docs.sqlalchemy.org/en/rel_1_0/core/selectable.html#sqlalchemy.sql.expression.CompoundSelect.cte