Python 如何编写带有连接和聚合的SQLAlchemy查询?
我有一个表,它有3列:type、content和time一个整数。对于每个“类型”,我要选择具有最大最近“时间”整数和相应数据的条目。如何使用SQLAlchemy和Python实现这一点?我可以使用SQL执行以下操作:Python 如何编写带有连接和聚合的SQLAlchemy查询?,python,sqlalchemy,Python,Sqlalchemy,我有一个表,它有3列:type、content和time一个整数。对于每个“类型”,我要选择具有最大最近“时间”整数和相应数据的条目。如何使用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 b
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
但是我怎样才能在炼金术中做到这一点呢
表映射:
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'选择structure.content作为structure\u content,anon\u 1.type作为
anon_1_类型,anon_1.t时间作为anon_1_时间\n从结构联接选择
time.max_1为max_1,structure.type为type,structure.time为time
\nFROM maxstructure.time AS time,structu re GROUP BY
structure.type为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
这可以通过使用SQLAlchemy来实现。你已经试过什么了吗?你有定义的表映射吗?@MartijnPieters嘿,Martijn,我昨晚在离开办公室的路上发布了这个。一旦我有机会再看一眼,我会给它添加一些代码;谢谢。@MartijnPieters到目前为止我已经添加了我的工作,但不知道我是否在正确的轨道上。赢家!感谢您的帮助,您已经澄清了我的主要问题以及一些较小的问题,如“我如何加入多个专栏?”,非常感谢您的帮助;谢谢