2015-10-17 91 views
0

我想執行使用SQLAlchemy的(與模型評價)這個SQL查詢:Sqlalchemy:如何執行外部連接?

select e1.user, sum(e1.points) as s from 
    (select e1.* 
    from evaluations e1 left outer join evaluations e2 
    on (e1.user = e2.user and e1.module = e2.module and e1.time < e2.time) 
    where e2.user is null and e1.module in (__another subquery__)) 
group by e1.user order by s limit 5 

我不知道如何執行左外連接(特別是具有重命名和更名comlumns的引用)。你可以幫幫我嗎?

+0

請參閱本文檔的[Using Aliases](http://docs.sqlalchemy.org/en/rel_1_0/orm/tutorial.html#using-aliases)部分。 'label'允許命名列。 – van

回答

1
# sample sub-query for testing 
_another_query = session.query(Evaluation.module).filter(Evaluation.module > 3) 

# define aliases 
E1 = aliased(Evaluation, name="e1") 
E2 = aliased(Evaluation, name="e2") 

# inner query 
sq = (
    session 
    # .query(E1) 
    # select columns explicitely to control labels 
    .query(E1.user.label("user"), E1.points.label("points")) 
    .outerjoin(E2, and_(
     E1.user == E2.user, 
     E1.module == E2.module, 
     E1.time < E2.time, 
    )) 
    .filter(E2.user == None) 
    .filter(E1.module.in_(_another_query)) 
) 
sq = sq.subquery(name="sq") 

# now lets group by 
q = (
    session 
    .query(sq.c.user, func.sum(sq.c.points)) 
    .group_by(sq.c.user) 
    .order_by(func.sum(sq.c.points)) 
    .limit(5) 
)