sql - "INSERT INTO tab SELECT * FROM another_tab"的 UPSERT

标签 sql sqlite select sql-update sql-insert

从另一个表中插入多行时,如何将“UPSERT”(插入或更新)插入到 SQLite 表中。

我试过:

INSERT INTO tab_name
SELECT * FROM tmp
ON CONFLICT(id)
    DO UPDATE SET
      val = excluded.val;

但它给了我:

syntax error near "DO"

实现该目标的正确且最有效的方法是什么?

最佳答案

您可能遇到了一个记录在案的名为 parsing ambiguity 的陷阱:

When the INSERT statement to which the UPSERT is attached takes its values from a SELECT statement, there is a potential parsing ambiguity. The parser might not be able to tell if the "ON" keyword is introducing the UPSERT or if it is the ON clause of a join. To work around this, the SELECT statement should always include a WHERE clause, even if that WHERE clause is just "WHERE true".)

那么,这样效果更好吗?

INSERT INTO tab_name
SELECT * FROM tmp WHERE true
ON CONFLICT(id) DO UPDATE SET val = excluded.val;

关于sql - "INSERT INTO tab SELECT * FROM another_tab"的 UPSERT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60981306/

相关文章:

c# - SQL 语句 - 如何编写带有通配符的 WHERE 子句

sql - 使用数据透视表为以下输出创建查询

sql - 避免用户向 SQL Server 中的存储过程提供空值

ios - 是否可以使用偏移/分页从 CoreStore 获取记录?

java - 关于 SQLite android 中的数组

php - SilverStripe 按精确顺序获取 id

sql - 在具有较少连接的关系中找到三个对象

MySQL - 从一周开始日期选择一周的数据

sql - SQL查询以选择不喜欢颜色变体的颜色

sql - 如何根据单个字段查询三个表