2015-09-08 33 views
6

我已經能夠使用文檔here中顯示的相關更新構造來更新表中的一列。SQLAlchemy多個列的相關更新

例如:

sel = select([UpdateTable.column]).\ 
     where(UpdateTable.id == OrigTable.id) 

up = update(OrigTable).values(column=sel) 

將會產生像SQL:

UPDATE origtable SET column=(SELECT updatetable.column 
FROM updatetable 
WHERE updatetable.id = origtable.id) 

是否有可能使用Declaritive或查詢API更新多個列的選擇?

我試圖仿效類似PostgreSQL中的以下內容:

UPDATE origtable 
    SET 
    column1 = updatetable.column1, 
    column2 = updatetable.column2 
    FROM updatetable 
    WHERE origtable.id == updatetable.id 

編輯:

看來,這個格式化單個語句可能無法與當前的SQLAlchemy API。

但是,使用here的解決方案似乎可以使用兩個選擇的解決方法。

+1

[該解決方案(http://stackoverflow.com/questions/30185056/updated-a-table-from-another-table-with-multiple-columns-in-sqlalchemy/30211905#30211905)並不是最優的,但可能已足夠滿足您的需求。 – lrnzcig

+0

謝謝@lrnzcig,我認爲這可能是可能的。 我猜目前的API不直接支持這個。 – amckinley

+0

不客氣。 (如果有幫助,我可以建議+1解決方案鏈接。謝謝。) – lrnzcig

回答

0

由於這是針對Postgresql的,我們可以使用SQLAlchemy的multiple table update支持。該文檔是唯一的核心,但Query API之上構建的核心,我們可以apply that knowledge

session.query(OrigTable).\ 
    filter(OrigTable.id == UpdateTable.id).\ 
    update({OrigTable.column1: UpdateTable.column1, 
      OrigTable.column2: UpdateTable.column2}, 
      synchronize_session=False) 

導致

UPDATE origtable 
SET column1=updatetable.column1, 
    column2=updatetable.column2 
FROM updatetable 
WHERE origtable.id = updatetable.id