如何使用SQLAlchemy为一个表创建左外连接

时间:2017-09-19 10:05:33

标签: python sql sqlalchemy flask-sqlalchemy

我很难理解如何在SQLAlchemy中使用针对单个表的左外连接。

我有以下SQL查询:

select r1.*, r1.result as result1, r2.result as result2 
from 
    (
        select * from participation 
        where day_id = 1 
        and sport_id = 1
    )
    r1 
left join 
    (
        select * from participation
        where day_id = 3
        and sport_id = 1
    )
    r2 
on r1.participant_id = r2.participant_id

这给了我以下结果集:

-------------------------------------------------------------------
| participant_id | sport_id | day_id | result | result1 | result2 |
-------------------------------------------------------------------
|              1 |        1 |      1 |      7 |       7 |       7 |
|              2 |        1 |      1 |     13 |      13 |         |
|              3 |        1 |      1 |      0 |       0 |       1 |
|              4 |        1 |      1 |      5 |       5 |       5 |
|              5 |        1 |      1 |     20 |      20 |      21 |
-------------------------------------------------------------------

我目前有以下SQLAlchemy脚本:

results = db.session.query(Participation). \
    <maybe something here?>
    all()

但是它会将每个结果作为自己的行返回。任何人都可以指出我需要做些什么吗?

1 个答案:

答案 0 :(得分:0)

根据您提供的信息,您只需要alias a subquery两次outerjoin

r1 = aliased(
    Participation,
    db.session.query(Participation).
        filter_by(day_id=1, sport_id=1).
        subquery())

r2 = aliased(
    Participation,
    db.session.query(Participation).
        filter_by(day_id=3, sport_id=1).
        subquery())

results = db.session.query(r1, r2.result, ...).\
    ...
    outerjoin(r2, r1.participant_id == r2.participant_id)