【问题标题】:SQLAlchemy: Using a CTE from a (sub)query w/ FROM clause specified as literal textSQLAlchemy:使用(子)查询中的 CTE 指定为文字文本的 FROM 子句
【发布时间】:2017-08-15 01:45:21
【问题描述】:

我有一个系统,用户可以在其中提供查询和 CTE 作为文本配置。一种可能的配置类似于以下内容:

import sqlalchemy as sa
cte = sa.select([sa.sql.text('* from foo')]).cte('foo_cte')
q = sa.select([sa.sql.text('* from (select * from foo_cte)')])

事实上,这个查询在渲染时不会包含 CTE 前导码:

>>> print q
SELECT * from (select * from foo_cte)

但是,如果我将所有可能的 CTE 添加到选择列表中:

q = q.select_from(cte)

...然后他们有额外的和无关的 FROM 子句由 SQLAlchemy 在渲染时添加,使语法无效:

>>> print q
WITH foo_cte AS
(SELECT * from foo)
 SELECT * from (select * from foo_cte)
FROM foo_cte

是否可以同时使用它——打印 CTE 序言而不将其添加到生成的 FROM 子句中?

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    如果您将q 定义为

    q = sa.select(['*']).select_from(cte)
    

    然后 sqlalchemy 能够找出要发出的正确 sql:

    import sqlalchemy as sa
    cte = sa.select([sa.text('* from foo')]).cte('foo_cte')    
    q = sa.select(['*']).select_from(cte)
    
    print(q)
    WITH foo_cte AS
    (SELECT * FROM foo)
     SELECT *
    FROM foo_cte
    

    【讨论】:

      猜你喜欢
      • 2021-03-01
      • 2013-08-16
      • 1970-01-01
      • 2019-04-22
      • 2014-02-12
      • 2021-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多