简体   繁体   English

在SqlAlchemy SQLite中的联合查询中按列排序

[英]Sort by a column in a union query in SqlAlchemy SQLite

As explained in this question , you can use string literals to do order by in union s. 就像在这个问题中所解释的那样,您可以使用字符串常量在union s中进行order by

For example, this works with Oracle: 例如,这适用于Oracle:

querypart1 = select([t1.c.col1.label("a")]).order_by(t1.c.col1).limit(limit)
querypart2 = select([t2.c.col2.label("a")]).order_by(t2.c.col2).limit(limit)
query = querypart1.union_all(querypart2).order_by("a").limit(limit)

The order-by can take a string literal, which is the name of the column in the union result. order-by可以采用字符串文字,这是联合结果中列的名称。

(There are gazillions of rows in partitioned tables and I'm trying to paginate the damn things) (分区表中有成千上万的行,我正试图对那些该死的东西进行分页)

When running against SQLite3, however, this generates an exception: 但是,在针对SQLite3运行时,会生成异常:

sqlalchemy.exc.OperationalError: (OperationalError) near "ORDER": syntax error

How can you order by the results of a union ? 您如何根据union的结果order by

The queries that are part of a union query must not be sorted. 联合查询中的查询不能排序。

To be able to use limits inside a compound query, you must wrap the individual queries inside a separate subquery: 为了能够在复合查询中使用限制,必须将单个查询包装在单独的子查询中:

SELECT * FROM (SELECT ... LIMIT ...)
UNION ALL
SELECT * FROM (SELECT ... LIMIT ...)
q1 = select(...).limit(...).subquery()
q2 = select(...).limit(...).subquery()
query = q1.union_all(q2)...

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

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