我正在尝试使用 SQLAlchemy 生成涉及 CTE 和联合的查询。不幸的是,每当我应用联合时,生成的 SQL 都不包含定义的 CTE。
这是包含 WITH 的 SQL,没有 UNION:
(Pdb) import sqlalchemy as sa
(Pdb) print str(sa.select([sa.select([sa.sql.null().label('a1')]).cte('bb')]))
WITH bb AS
(SELECT NULL AS a1)
SELECT bb.a1
FROM bb
现在是相同的查询,但调用了 union:
(Pdb) print str(sa.select([sa.select([sa.sql.null().label('a1')]).cte('bb')]).union_all(sa.select([sa.sql.null().label('b1')])))
SELECT bb.a1
FROM bb UNION ALL SELECT NULL AS b1
我希望联合调用的查询仍然包含 WITH,但它没有。
最佳答案
我相信这是一个错误。我应用了以下补丁来使 UNION 与 CTE 一起工作:
--- sqlalchemy.orig/sql/compiler.py 2012-05-20 17:39:41.000000000 +0000
+++ sqlalchemy/sql/compiler.py 2012-05-20 17:39:00.000000000 +0000
@@ -562,6 +562,15 @@
text += (cs._limit is not None or cs._offset is not None) and \
self.limit_clause(cs) or ""
+ if self.ctes and \
+ compound_index==1 and not entry:
+ cte_text = self.get_cte_preamble(self.ctes_recursive) + " "
+ cte_text += ", \n".join(
+ [txt for txt in self.ctes.values()]
+ )
+ cte_text += "\n "
+ text = cte_text + text
+
self.stack.pop(-1)
if asfrom and parens:
return "(" + text + ")"
关于python - 使用带有 CTE 的联合时,由 sqlalchemy 生成的格式错误的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10663445/