使用SQLAlchemy限制子查询

时间:2014-08-18 15:03:32

标签: python sql postgresql sqlalchemy relational-database

我在SQLAlchemy中定义了几个模型:

class Location(Base):
    __tablename__ = 'Location'
    __table_args__ = {u'schema': 'Location'}

    Unit_id = Column(ForeignKey(u'Structure.Definition.Unit_id', ondelete=u'RESTRICT', onupdate=u'CASCADE'), primary_key=True, nullable=False)
    Timestamp = Column(DateTime, primary_key=True, nullable=False)
    Latitude = Column(Float)
    Longitude = Column(Float)


class Definition(Base):
    __tablename__ = 'Definition'
    __table_args__ = {u'schema': 'Structure'}

    Unit_id = Column(Integer, primary_key=True)
    Name = Column(String(90))

    Location = relationship(u'Location')

我有疑问:

sub = DBSession.query(Location.Unit_id, func.max(Location.Timestamp).label('latest_timestamp')).\
    filter(Location.Latitude != None, Location.Longitude != None).\
    group_by(Location.Unit_id).\
    subquery()

res = DBSession.query(Definition).\
    join((sub, sub.c.Unit_id == Definition.Unit_id)).\
    all()

我的查询结果是很少Definition个对象,每个对象都有Location个。但是,我想查询所有Definition行,但只有Locations表中的最后行,每行Definition行。< / p>

考虑到Location表已经包含数十万行,最好的查询方式是什么?

1 个答案:

答案 0 :(得分:0)

好吧,你似乎根本没有使用子查询中的latest_timestamp,这看起来完全是浪费。此外,您的查询只会返回 Definition个实例。

请改为尝试:

res = DBSession.query(Definition, Location).\
    join(Location, Definition.Location).\
    join((sub, and_(sub.c.Unit_id == Definition.Unit_id, 
                    sub.c.latest_timestamp == Location.Timestamp)).\
    all()


for defi, loca in res:
    print(defi, loca)

注意:我希望locations代替Location作为关系的名称。