[英]How to create a left outer join to one table using 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()
但這會將每個結果返回為自己的行。 誰能指出我需要做些什么?
有了給出的信息,您只需要對子 查詢使用兩次別名並使用externaljoin :
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.