从子查询更新多个列

2021-04-11 14:47:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用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条回答
网友
1楼 ·

您需要^{}^{}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)

剩下的(执行等)由你决定,因为问题是关于细节的。在

相关问题