【问题标题】:How to upsert based on values from another table?如何根据另一个表中的值进行更新插入?
【发布时间】:2021-09-07 23:13:18
【问题描述】:

我正在尝试使用 PeeWee 根据另一个表中的值 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 中找到合适的 peewee 示例。

【问题讨论】:

标签: postgresql peewee


【解决方案1】:

给你:

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

【讨论】:

  • 完美运行。
猜你喜欢
  • 2018-10-08
  • 2023-03-26
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-10
  • 1970-01-01
  • 2019-08-20
相关资源
最近更新 更多