我有一个查询要求我加入一段时间,如2012年,2013年和2014年。即使没有年度值,所有年份都需要返回行。在SQL中,这看起来像:
SELECT
*
FROM
kpi.unit_type_row_model
CROSS JOIN
( SELECT 2012 AS Year UNION ALL SELECT 2013 UNION ALL SELECT 2014 ) AS Y
-- MORE JOINS FOR GETTING VALUES
如何创建子查询:
SELECT 2012 AS Year UNION ALL SELECT 2013 UNION ALL SELECT 2014
2012年,2013年和2014年以价值形式发送,工会必须即时创建。
答案 0 :(得分:1)
CROSS JOIN
中没有明确的sqlalchemy
。通过简单地从两个(或更多)表中选择而没有任何join
条件,可以获得类似的效果。 text
构建。将两者结合在一起,这是解决方案:
years = range(2012, 2016)
txt = " UNION ALL ".join("SELECT {} AS Year".format(y) for y in years)
stmt = text(txt).columns(Year=Integer) # @note: works only on sqlachemy >= 0.9
# stmt = text(txt, typemap={'Year': Integer}) # note: fall back for SA version < 0.9
q = session.query(MyClass, stmt) # @note: since there is no JOIN, it will return cartesian product
for row in q.all():
print(row)