Python SQLAlchemy使用标记的OVER子句和ORM进行查询

问题描述 投票:6回答:3

另一个问题是如何在sqlalchemy上使用OVER子句:

Using the OVER window function in SQLAlchemy

但是如何使用ORM呢?我有类似的东西:

q = self.session.query(self.entity, func.count().over().label('count_over'))

当我使用以下消息调用q.all()时失败:

sqlalchemy.exc.InvalidRequestError:
Ambiguous column name 'count(*) OVER ()' in result set! try 'use_labels' option on select statement

我怎么解决这个问题?

python sqlalchemy
3个回答
4
投票

你有几乎正确的over语法,它应该是这样的:

import sqlalchemy
q = self.session.query(
    self.entity,
    sqlalchemy.over(func.count()).label('count_over'),
)

来自文档的示例:

from sqlalchemy import over
over(func.row_number(), order_by='x')

2
投票

SQLAlchemy Query对象具有with_entities方法,可用于自定义查询返回的列列表:

Model.query.with_entities(Model.foo, func.count().over().label('count_over'))

导致以下SQL:

SELECT models.foo AS models_foo, count(*) OVER () AS count_over FROM models

0
投票

你的功能正确。他们使用它们产生预期结果的方式如下:

from sqlalchemy import func
q = self.session.query(self.entity, func.count(self.entity).over().label('count_over'))

这将生成一个COUNT(*)语句,因为没有指定Entity.field。我使用以下格式:

from myschema import MyEntity
from sqlalchemy import func
q = self.session.query(MyEntity, func.count(MyEntity.id).over().label('count'))

那就是当然有一个id字段。但是你得到了机制:-)

© www.soinside.com 2019 - 2024. All rights reserved.