Sqlalchemy:如何与自己进行外连接?

时间:2015-10-17 10:03:08

标签: python sqlalchemy

我想使用Sqlalchemy(带模型评估)执行此SQL查询:

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的重命名和引用)。你能帮帮我吗?

1 个答案:

答案 0 :(得分: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)
)