我有一個表有3列:類型,內容和時間(一個整數)。對於每個'類型',我想選擇具有最大(最近)'時間'整數和相應數據的條目。我怎樣才能使用SQLAlchemy和Python來做到這一點?我可以使用SQL執行以下操作:如何使用Join和Aggregate編寫SQLAlchemy查詢?
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) near "(": syntax error u'SELECT structure.content AS structure_content, anon_1.type AS anon_1_type, anon_1.t ime AS anon_1_time \nFROM structure JOIN (SELECT time.max_1 AS max_1, structure.type AS type, structure.time AS time \nFROM max(structure.time) AS time, structu re GROUP BY structure.type) AS anon_1 ON structure.type = anon_1.type'()
我基本上是在黑暗中刺傷,所以任何幫助將是讚賞。
這可以使用SQLAlchemy的完成。你有沒有嘗試過任何東西?你有沒有定義任何表映射? –
@MartijnPieters Hey Martijn,我昨晚在出去辦公室的路上發了這篇文章。一旦我有機會再看一次,我會添加一些代碼;謝謝。 –
@MartijnPieters我已經添加了我的工作到目前爲止,不知道如果我在正確的軌道上。 –