如何根据另一个 table 的值进行更新?

How to upsert based on values from another table?

我正在尝试使用 PeeWee 根据来自另一个 table 的值将 UPSERT 插入到 postgres 数据库中。

**table1**
pk_t1 int
name
city
country
**table2**
pk_t2 int
name
city
country
comments
INSERT INTO table2 (pk_t2, name, city, country) 
SELECT pk_1, name, city, country
FROM   table1
ON     CONFLICT (pk_t2) DO UPDATE  
SET    name = excluded.name, city = excluded.city, country = excluded.country;           

但我无法从文档或 SO 中找到 suitable peewee 示例。

给你:

q = T1.select()

iq = (T2
      .insert_from(q, fields=[T2.id, T2.name, T2.city, T2.country])
      .on_conflict(conflict_target=[T2.id], preserve=[T2.name, T2.city, T2.country]))

对应SQL peewee生成:

insert into t2 (id, name, city, country)
select t1.id, t1.name, t1.city, t1.country
from t1
on conflict(id) do update set 
  name=excluded.name,
  city=excluded.city,
  country=excluded.country