简体   繁体   English

结合2个sqlalchemy查询和排序

[英]Combining 2 sqlalchemy queries and sorting

I'm using the results of one query to process another and then add that data to the original query object.我正在使用一个查询的结果来处理另一个查询,然后将该数据添加到原始查询 object 中。 I'd then like to order the results by that data.然后,我想按该数据排序结果。

Here's what I have at the moment:这是我目前所拥有的:

def driver():
    sess = session()
    data = sess.query(DriversConstructors).filter(DriversConstructors.TYPE_ID==1).all()
    for driver in data:
        p = sess.query(func.sum(FantasyResults.POINTS)).filter(FantasyResults.DRIVER_CONSTRUCTOR_ID==driver._ID).scalar()
        driver.points = int(p)
    sess.close()
    return data

so basically the results need to be ordered by points.所以基本上结果需要按点排序。

I'm pretty confident there is a much better way of doing this so any help would be appreciated.我非常有信心有更好的方法来做到这一点,所以任何帮助都将不胜感激。

If I have understood correctly, what you need is a JOIN and some grouping in order to move the operation to the database system:如果我理解正确,您需要的是 JOIN 和一些分组,以便将操作移动到数据库系统:

def driver(type_id=1):
    sess = session()
    try:
        return sess.query(DriversConstructors).\
            outerjoin(FantasyResults,
                      FantasyResults.DRIVER_CONSTRUCTOR_ID == DriversConstructors._ID). \
            filter(DriversConstructors.TYPE_ID == type_id). \
            group_by(DriversConstructors._ID). \
            order_by(func.sum(FantasyResults.POINTS)). \
            all()

    finally:
        sess.close()

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

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