SQLAlchemy ORM:LEFT JOIN LATERAL()正确
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQLAlchemy ORM:LEFT JOIN LATERAL()正确相关的知识,希望对你有一定的参考价值。
我试图复制以下原始查询:
SELECT r.id, r.name, e.id, e.title, e.start, e.end
FROM room r
LEFT JOIN LATERAL (
SELECT evt.id, evt.title, evt.start, evt.end
FROM event evt, calendar cal
WHERE
r.calendar_id=cal.id AND evt.calendar_id=cal.id AND evt.end>%(start)s
ORDER BY abs(extract(epoch from (evt.start - %(start)s)))
LIMIT 1
) e ON TRUE
WHERE r.company_id=%(company_id)s;
使用SQLAlchemy ORM:
start = datetime.datetime.now()
company_id = 6
event_include = session.query(
Event.id,
Event.title,
Event.start,
Event.end)
.filter(
Room.calendar_id == Calendar.id,
Event.calendar_id == Calendar.id,
Event.end > start,
)
.order_by(func.abs(func.extract('epoch', Event.start - start)))
.limit(1)
.subquery()
.lateral()
query = session.query(Room.id, Room.name, event_include)
.filter(Room.company_id == company_id)
其中产生以下SQL:
SELECT room.id AS room_id, room.name AS room_name, anon_1.id AS anon_1_id, anon_1.title AS anon_1_title, anon_1.start AS anon_1_start, anon_1."end" AS anon_1_end
FROM room, LATERAL (
SELECT event.id AS id, event.title AS title, event.start AS start, event."end" AS "end"
FROM event, calendar
WHERE room.calendar_id = calendar.id AND event.calendar_id = calendar.id AND event."end" > %(end_1)s ORDER BY abs(EXTRACT(epoch FROM event.start - %(start_1)s)
)
LIMIT %(param_1)s) AS anon_1
WHERE room.company_id = %(company_id_1)s
这会返回所有房间及其下一个日历活动,但前提是有下一个日历活动可用。它需要是一个LEFT JOIN LATERAL() ON TRUE
,但我不知道该怎么做。
这里的任何帮助都会很棒。
答案
from sqlalchemy import true
query = session.query(Room.id, Room.name, event_include)
.outerjoin(event_include, true())
.filter(Room.company_id == company_id)
以上是关于SQLAlchemy ORM:LEFT JOIN LATERAL()正确的主要内容,如果未能解决你的问题,请参考以下文章
尝试在 sqlalchemy orm 查询中加入两个表,出现错误
如何从 SQLAlchemy JOIN 中的两个表返回结果?