简体   繁体   English

如何在SQLAlchemy中过滤union_all的结果?

[英]How to filter the result of union_all in SQLAlchemy?

I have two SQLAlchemy tables generated by reflection using SQLAlchemy: 我有两个使用SQLAlchemy反射生成的SQLAlchemy表:

In [356]: t1
Out[356]: Table('t1', MetaData(bind=None), Column('x', INT(), table=<t1>), Column('y', STRING(), table=<t1>), schema=None)

In [357]: t2
Out[357]: Table('t2', MetaData(bind=None), Column('x', INT(), table=<t2>), Column('y', STRING(), table=<t2>), schema=None)

I would like to do a union_all operation using the above two tables, and then filter the result to keep only when x > 2 . 我想使用上面的两个表进行union_all操作,然后过滤结果以仅在x > 2时保留。 Here is what I did: 这是我所做的:

q1 = select([t1.c.x.label('x'), t1.c.y.label('y')])
q2 = select([t2.c.x.label('x'), t2.c.y.label('y')])
q3 = q1.union_all(q2)
q = select([q3.c.x, q3.c.y]).where(q3.c.x > 2)
conn.execute(q).fetchall()

But I got: 但是我得到了:

DBAPIError: (impala.error.HiveServer2Error) AnalysisException: Syntax error in line 5:
WHERE x > 2
^
Encountered: WHERE
Expected: AS, DEFAULT, IDENTIFIER

CAUSED BY: Exception: Syntax error
 [SQL: 'SELECT x, y \nFROM (SELECT t1.x AS x, t1.y AS y \nFROM t1 UNION ALL SELECT t2.x AS x, t2.y AS y \nFROM t2) \nWHERE x > %(x_1)s'] [parameters: {'x_1': 2}] (Background on this error at: http://sqlalche.me/e/dbapi)

Have found similar questions here and here , but still no idea. 在这里这里都发现了类似的问题,但仍然不知道。

Your derived table has no name, or in other words the union expression is missing an alias in the FROM clause. 您的派生表没有名称,换句话说,联合表达式在FROM子句中缺少别名。 Try: 尝试:

q3 = q1.union_all(q2).alias()

which will add the required AS. 这将添加所需的AS。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM