繁体   English   中英

如何使用Join和Aggregate编写SQLAlchemy查询?

[英]How can I write an SQLAlchemy Query with a Join and an Aggregate?

我有一个有3列的表:类型,内容和时间(整数)。 对于每个'类型',我想选择具有最大(最近)'时间'整数的条目和相应的数据。 我怎么能用SQLAlchemy和Python做到这一点? 我可以使用SQL执行以下操作:

select
  c.type,
  c.time,
  b.data
from
  parts as b

inner join

  (select
    a.type,
    max(a.time) as time
  from parts as a
  group by a.type) as c

on

b.type = c.type and
b.time = c.time

但是我怎样才能在SQLAlchemy中实现这一目标?

表映射:

class Structure(Base):
    __tablename__ = 'structure'
    id = Column(Integer, primary_key=True)
    type = Column(Text)
    content = Column(Text)
    time = Column(Integer)

    def __init__(self, type, content):
        self.type = type
        self.content = content
        self.time = time.time()

    def serialise(self):
        return {"type" : self.type,
            "content" : self.content};

尝试查询:

    max = func.max(Structure.time).alias("time")
    c = DBSession.query(max)\
        .add_columns(Structure.type, Structure.time)\
        .group_by(Structure.type)\
        .subquery()
    c.alias("c")

    b = DBSession.query(Structure.content)\
        .add_columns(c.c.type, c.c.time)\
        .join(c, Structure.type == c.c.type)

给我:

sqlalchemy.exc.OperationalError :( OperationalError)靠近“(”:语法错误u'SELECT structure.content AS structure_content,anon_1.type AS anon_1_type,anon_1.t ime AS anon_1_time \\ nFROM结构JOIN(SELECT time.max_1 AS max_1,structure .type AS类型,structure.time AS时间\\ nFROM max(structure.time)AS时间,结构GROUP BY structure.type)AS anon_1 ON structure.type = anon_1.type'()

我基本上是在黑暗中刺伤,所以任何帮助都会受到赞赏。

使用子查询尝试以下代码:

subq = (session.query(
            Structure.type, 
            func.max(Structure.time).label("max_time")
        ).
        group_by(Structure.type)
        ).subquery()

qry = (session.query(Structure).
       join(subq, and_(Structure.type == subq.c.type, Structure.time == subq.c.max_time))
       )

print qry

产生SQL:

SELECT  structure.id AS structure_id, structure.type AS structure_type, structure.content AS structure_content, structure.time AS structure_time
FROM    structure 
JOIN    (SELECT structure.type AS type, max(structure.time) AS max_time
         FROM structure GROUP BY structure.type) AS anon_1 
    ON  structure.type = anon_1.type 
    AND structure.time = anon_1.max_time

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM