[英]How can I update one column in a right outer join style query in SQLAlchemy (PostgreSQL/Python)?
我有兩個表, Table A
和Table B
我在Table A
添加了一列record_id
。 Table B
具有record_id
和Table A
的主要ID table_a_id
。 我打算棄用Table B
如果有幫助,則Table B
的table_a_id
與Table A
的id
之間存在關系。
目前,我的解決方案是:
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.