简体   繁体   English

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

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

I have two tables, Table A and Table B . 我有两个表, Table ATable B I have added one column to Table A , record_id . 我在Table A添加了一列record_id Table B has record_id and the primary ID for Table A , table_a_id . Table B具有record_idTable A的主要ID table_a_id I am looking to deprecate Table B . 我打算弃用Table B

Relationships exist between Table B 's table_a_id and Table A 's id , if that helps. 如果有帮助,则Table Btable_a_idTable Aid之间存在关系。

Currently, my solution is: 目前,我的解决方案是:

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

This is my first time using this ORM -- I'd like to see if there is a way I can use my Python models and the actual functions SQLAlchemy gives me to be more 'Pythonic' rather than just dumping a Postgres statement that I know works in an execute call. 这是我第一次使用此ORM,我想看看是否有一种方法可以使用我的Python模型,而SQLAlchemy的实际功能使我变得更“ Pythonic”,而不仅仅是转储我知道的Postgres语句在执行调用中工作。

My solution ended up being as follows: 我的解决方案最终如下:

(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))

This leverages the ability of PostgreSQL to do updates based on implicit references of other tables, which I did in my .filter() call (this is analogous to a WHERE in a JOIN query). 这利用了PostgreSQL基于其他表的隐式引用进行更新的能力,这是我在.filter()调用中所做的(这类似于JOIN查询中的WHERE)。 The solution was deceivingly simple. 解决方案非常简单。

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

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