从子查询更新多个列

时间:2017-04-20 12:02:55

标签: python sqlalchemy

我想使用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);

非常感谢您的帮助

1 个答案:

答案 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)

其余的(执行等)取决于你,因为问题很清楚。