我想使用SQLAlchemy创建以下语句。它可以在数据库上完全执行,因此不涉及将任何数据检索到sqlalchemy层。
UPDATE summary s SET (sum_x, sum_y, avg_x, avg_y) =
(SELECT sum(x), sum(y), avg(x), avg(y) FROM data d
WHERE d.group_id = s.group_id);
非常感谢您的帮助
答案 0 :(得分:1)
您需要tuple_()
,self_group()
和correlated subquery:
In [9]: from sqlalchemy import tuple_
In [10]: stmt = select([func.sum(data.c.x),
...: func.sum(data.c.y),
...: func.avg(data.c.x),
...: func.avg(data.c.y)]).\
...: where(data.c.group_id == summary.c.group_id)
In [11]: summary.update().\
...: values({ tuple_(summary.c.sum_x,
...: summary.c.sum_y,
...: summary.c.avg_x,
...: summary.c.avg_y).self_group(): stmt })
Out[11]: <sqlalchemy.sql.dml.Update object at 0x7ff76a80a908>
In [12]: print(_)
UPDATE summary SET (sum_x, sum_y, avg_x, avg_y)=(SELECT sum(data.x) AS sum_1, sum(data.y) AS sum_2, avg(data.x) AS avg_1, avg(data.y) AS avg_2
FROM data
WHERE data.group_id = summary.group_id)
其余的(执行等)取决于你,因为问题很清楚。