SQLAlchemy加入子查询问题

时间:2015-05-18 19:27:43

标签: python sqlalchemy

我正在尝试将SQL转换为SQLAlchemy。我想要的查询的SQL版本如下:

SELECT * from calendarEventAttendee
JOIN calendarEventAttendanceActual ON calendarEventAttendanceActual.id = calendarEventAttendee.attendanceActualId
LEFT JOIN
   (SELECT bill.id, bill.personId, billToEvent.eventId FROM bill JOIN billToEvent ON bill.id = billToEvent.billId) b 
   ON b.eventId = calendarEventAttendee.eventId AND b.personId = calendarEventAttendee.personId
WHERE b.id is NULL

我的SQLAlchemy查询如下:

query = db.session.query(CalendarEventAttendee).join(CalendarEventAttendanceActual)

sub_query = db.session.query(Bill, BillToEvent).join(BillToEvent, BillToEvent.billId == Bill.id).subquery()
query = query.outerjoin(sub_query, and_(sub_query.Bill.personId == CalendarEventAttendee.personId, Bill.eventId == CalendarEventAttendee.eventId))
results = query.all()

我收到错误AttributeError: 'Alias' object has no attribute 'Bill'

如果我将SQLAlchemy查询调整为以下内容:

sub_query = db.session.query(Bill, BillToEvent).join(BillToEvent, BillToEvent.billId == Bill.id).subquery()
query = query.outerjoin(sub_query, and_(sub_query.Bill.personId == CalendarEventAttendee.personId, sub_query.BillToEvent.eventId == CalendarEventAttendee.eventId))

results = query.all()

我收到错误AttributeError: Bill

任何帮助将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:20)

致电subquery()后,无法访问对象,只能通过.c.{column_name}访问者访问列。

sub_query执行以下操作:仅加载您需要的列以避免任何名称冲突:

sub_query = db.session.query(
        Bill.id, Bill.personId, BillToEvent.eventId
    ).join(BillToEvent, BillToEvent.billId == Bill.id).subquery()

然后在您的查询中使用带有.c.column_name的列名:

query = query.outerjoin(
    sub_query, and_(
        sub_query.c.personId == CalendarEventAttendee.personId, 
        sub_query.c.eventId == CalendarEventAttendee.eventId)
    )
results = query.all()