SQLAlchemy:查询每年的最高金额

时间:2015-07-12 21:47:31

标签: python performance sqlalchemy flask-sqlalchemy

我有一个带有日期列的模型Photo。我正在制作一个照片库,其中包含概览视图,每年最多可显示5张照片。

目前我有这个查询,并让它循环通过手工制作的年份列表。
(即for year in range(2000, 2016):

Photo.query \
.filter(extract('year', Photo.date)==year) \
.order_by(Photo.date) \
.limit(5) \
.all()

是否有更有效的方法(而不是15个查询)?此外,但不太重要的是,有没有一种方法可以根据照片的存在年份(作为使用硬编码列表的替代方法)对年份进行排序?

更新:我正在使用sqlite3

1 个答案:

答案 0 :(得分:1)

假设date是唯一的,下面的查询应适用于sqlite

# define aliases as we will need to join the table on itself
p1 = Photo
p2 = db.aliased(Photo, name='p2')

q = (
    p1.query
    # join *Photo* on itself and count the *rank* of current photo by counting the photos with date before it in the same year
    .join(p2, sa.and_(
        sa.func.extract("year", p1.date) == sa.func.extract("year", p2.date),
        p1.date >= p2.date,
    ))
    .group_by(p1.id)
    .having(sa.func.count() <= 5)
    .order_by(p1.date)  # This will automatically order by year and rank
)

如果date不是唯一的,但几乎唯一,那么结果将不会总是5行,但可以更多或更少。如果这些值确实是date值(没有时间分量),请告诉我 - 应该很容易获得更强大的解决方案。

相关问题