简体   繁体   English

INSERT INTO 子查询和 ON CONFLICT

[英]INSERT INTO with subquery and ON CONFLICT

I want to insert all elements from a JSON array into a table:我想将 JSON 数组中的所有元素插入到表中:

INSERT INTO local_config(parameter, value)
SELECT json_extract(j.value, '$.parameter'), json_extract(j.value, '$.value')
FROM json_each(json('[{"parameter": 1, "value": "value1"}, {"parameter": 2, "value": "value2"}]')) AS j
WHERE value LIKE '%'
ON CONFLICT (parameter) DO UPDATE SET value = excluded.value;

This works so far, but do I really need the WHERE value LIKE '%' clause?到目前为止这是可行的,但我真的需要WHERE value LIKE '%'子句吗?

When I remove it:当我删除它时:

INSERT INTO local_config(parameter, value)
SELECT json_extract(j.value, '$.parameter'), json_extract(j.value, '$.value')
FROM json_each(json('[{"parameter": 1, "value": "value1"}, {"parameter": 2, "value": "value2"}]')) AS j
ON CONFLICT (parameter) DO UPDATE SET value = excluded.value;

I get this error:我收到此错误:

[SQLITE_ERROR] SQL error or missing database (near "DO": syntax error)

From SQL As Understood By SQLite/Parsing Ambiguity :SQL 可以理解为 SQLite/解析歧义

When the INSERT statement to which the UPSERT is attached takes its values from a SELECT statement, there is a potential parsing ambiguity.当 UPSERT 附加到的 INSERT 语句从 SELECT 语句中获取其值时,存在潜在的解析歧义。 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.解析器可能无法判断“ON”关键字是否引入了 UPSERT 或者它是否是连接的 ON 子句。 To work around this, the SELECT statement should always include a WHERE clause, even if that WHERE clause is just "WHERE true".要解决此问题,SELECT 语句应始终包含一个 WHERE 子句,即使该 WHERE 子句只是“WHERE true”。

So you need the WHERE clause, but it can be a simple WHERE true or just WHERE 1 .所以你需要 WHERE 子句,但它可以是一个简单的WHERE true或只是WHERE 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 冲突时忽略-如果存在冲突而不是忽略,如何将数据插入重复表 - ON CONFLICT IGNORE - How to insert data into a dupes table if there is a conflict instead of ignoring SQLite,根据联合子查询的结果插入或忽略 - SQLite, insert or ignore based on result of a union subquery 使用 INSERT INTO 和子查询 SELECT 插入字段的前一个值 - Insert previous value of field using INSERT INTO and subquery SELECT Peewee - 插入许多 - 冲突时 - 正确的查询结构以在冲突时保留指定字段? - Peewee - Insert Many - On Conflict - Proper query structure to preserve specified fields on conflict? 如何使用 ON CONFLICT REPLACE 策略使用 SQLITE 进行 INSERT? - How can I do INSERT with SQLITE with ON CONFLICT REPLACE strategy? Python SQLITE3 插入和冲突时更新变量 - 语法问题? - Python SQLITE3 Insert into and On conflict do update with variables - Syntax problem? 替代 SQLite INSERT... ON CONFLICT... WHERE... DO UPDATE SET - Alternative to SQLite INSERT ... ON CONFLICT ... WHERE ... DO UPDATE SET Android SQLITE插入表中的值来自子查询 - Android SQLITE Insert into table with values coming from a subquery 如何在sqlite的SELECT语句中将INSERT用作子查询? - How can i use INSERT as subquery in SELECT statement in sqlite? 子查询实现 - Subquery implementation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM