在SQLAlchemy Core中替换现有记录

1 投票
1 回答
668 浏览
提问于 2025-04-18 18:08

我想把一个表里的旧记录替换成另一个新表里相同键的记录。

在SQL中,比如,我只需要执行以下两个语句:

DELETE O FROM OLD_TABLE T1
    WHERE EXISTS (SELECT * FROM NEW_TABLE T2
                  WHERE T1.KeyPart1 = T2.KeyPart1
                  AND   T1.KeyPart2 = T2.KeyPart2 )

INSERT OLD_TABLE 
     SELECT * FROM NEW_TABLE T2
     WHERE NOT EXISTS (SELECT * FROM OLD_TABLE T1
                        WHERE T1.KeyPart1 = T2.KeyPart1
                        AND   T1.KeyPart2 = T2.KeyPart2)

那么在Python中,我该如何使用SQLAlchemy Core(不是ORM)来做到这一点呢?

OldTable.delete().????   
OldTable.insert(NewTable.select()) ????

我现在完全搞不清楚状况。

附注:我之所以使用SQLAlchemy CORE,是因为(a)记录很多,(b) 我希望SQLAlchemy能处理数据库方言的依赖问题。

相关问题:

1 个回答

1

在 SQL 查询中,"exists" 是通过 WHERE 子句来处理的,使用的是 exists() 这个函数。而 "INSERT .. FROM SELECT" 则是通过 from_select() 来实现的。

conn.execute(
   old_table.delete().where(exists().where(
              old_table.c.col == new_table.c.col
             ).where(
              old_table.c.col2 == new_table.c.col2).
              correlate(old_table)
   )
)

conn.execute(
      old_table.insert().from_select(['col', 'col2'], new_table.select().where(
      ~exists().where(old_table.c.col == new_table.c.col).correlate(new_table)
      )    
)

撰写回答