sqlalchemy创建一个整数列表作为子查询

时间:2014-04-13 19:43:17

标签: python sqlalchemy union

我有一个查询要求我加入一段时间,如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年以价值形式发送,工会必须即时创建。

1 个答案:

答案 0 :(得分:1)

  1. 正如Is explicit CROSS JOIN possible with SQLAlchemy?的回答中指出的那样,CROSS JOIN中没有明确的sqlalchemy。通过简单地从两个(或更多)表中选择而没有任何join条件,可以获得类似的效果。
  2. 要获得第二个选择,只需使用text构建。
  3. 将两者结合在一起,这是解决方案:

    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)