タイプ、コンテンツ、時間 (整数) の 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) near "(": 構文エラー u'SELECT structure.content AS structure_content、anon_1.type AS anon_1_type、anon_1.time AS anon_1_time \nFROM 構造 JOIN (SELECT time.max_1 AS max_1、構造.type AS type, structure.time AS time \nFROM max(structure.time) AS time, structure GROUP BY structure.type) AS anon_1 ON structure.type = anon_1.type' ()
私は本質的に暗闇の中で刺しているので、どんな助けもいただければ幸いです.