SqlAlchemy Left加入计数

时间:2012-02-28 07:22:31

标签: python count sqlalchemy left-join

class Employee
    id
    name

class Location
    id
    city

class Work
    id
    employee_id
    location_id

Todo:左计数加入(包括零)

期望的结果

    location.city count
    NYC 10
    SFO 5
    CHI 0

原始查询:

    select location.id, count(work.id) as count
    from location 
    left join work
    on location.id = work.location_id
    group by location.id

SQLAlchemy的:

    db_session.query(Location, func.count.work_id).label('count')). \
                filter(location.id == work.location_id). \
                group_by(location._id). \

在执行左连接时,在select中指定列的正确方法是什么?

1 个答案:

答案 0 :(得分:8)

定义orm模型时定义表之间的关系。见this tutorial。在您的示例中,Work是一个关联表,因此,如果您在Work中没有任何其他数据,则可以使用many to many relationship,例如:

from sqlalchemy.orm import relationship

class Work
    id
    employee_id
    location_id

class Employee
    id
    name

class Location
    id
    city
    employees = relationship(Employee, secondary=Work, backref='locations')

然后查询:

session.query(Location, func.count(Work.id)).outerjoin(Work).group_by(Location)

正如您已定义关系一样,sqlalchemy将知道outerjoin的方向和列。

当您执行group_by时,传递Location而不仅仅是Location.id非常重要,因为通过执行select(Location),sqlalchemy将选择位置中的所有列,并且所以你还必须传递位置中的所有列。