繁体   English   中英

如何在SQLAlchemy(PostgreSQL / Python)中的右外部联接样式查询中更新一列?

[英]How can I update one column in a right outer join style query in SQLAlchemy (PostgreSQL/Python)?

我有两个表, Table ATable B 我在Table A添加了一列record_id Table B具有record_idTable A的主要ID table_a_id 我打算弃用Table B

如果有帮助,则Table Btable_a_idTable Aid之间存在关系。

目前,我的解决方案是:

db.execute("UPDATE table_a t 
   SET record_id = b.record_id 
   FROM table_b b 
   WHERE t.id = b.table_a_id")

这是我第一次使用此ORM,我想看看是否有一种方法可以使用我的Python模型,而SQLAlchemy的实际功能使我变得更“ Pythonic”,而不仅仅是转储我知道的Postgres语句在执行调用中工作。

我的解决方案最终如下:

(db.query(TableA)
        .filter(TableA.id == TableB.table_a_id,
        TableA.record_id.is_(None))
        .update({TableA.record_id: TableB.record_id}, synchronize_session=False))

这利用了PostgreSQL基于其他表的隐式引用进行更新的能力,这是我在.filter()调用中所做的(这类似于JOIN查询中的WHERE)。 解决方案非常简单。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM