SQLite中NOT EXISTS校验后插入多行出现语法错误求助
解决SQLite插入多行时的语法错误问题
我来帮你搞定这个SQL语法错误的问题~你遇到的syntax error near "("主要是因为SQLite对VALUES子句作为子查询数据源的支持有版本限制,再加上你的SELECT子句存在列数不匹配的问题,咱们一步步解决:
错误原因分析
- SQLite版本兼容问题:在SQLite 3.33.0(2020年发布)之前,数据库不支持直接将
VALUES()子句作为子查询的数据源,这就是你看到语法错误的核心原因。 - 列数不匹配:你的
INSERT语句需要插入3个字段,但SELECT子句只选取了associatedEmotion一个字段,即使语法问题解决,后续也会触发列数不匹配的错误。
修正后的SQL代码
方法1:兼容所有SQLite版本(推荐)
用UNION ALL拼接多行数据,这种写法在所有SQLite版本中都能正常运行,同时修正列数问题:
INSERT INTO words (associatedEmotion, word, severity) SELECT newWords.associatedEmotion, newWords.word, newWords.severity FROM ( SELECT 'joy' AS associatedEmotion, 'ecstatic' AS word, '3' AS severity UNION ALL SELECT 'joy' AS associatedEmotion, 'happy' AS word, '2' AS severity ) AS newWords WHERE NOT EXISTS ( SELECT 1 FROM words AS MT WHERE MT.associatedEmotion = newWords.associatedEmotion );
方法2:适用于SQLite 3.33.0及以上版本
如果你的SQLite版本足够新,可以直接使用VALUES子句,但要确保正确指定别名和列定义,同时选取所有需要插入的字段:
INSERT INTO words (associatedEmotion, word, severity) SELECT newWords.associatedEmotion, newWords.word, newWords.severity FROM ( VALUES ('joy', 'ecstatic', '3'), ('joy', 'happy', '2') ) AS newWords (associatedEmotion, word, severity) WHERE NOT EXISTS ( SELECT 1 FROM words AS MT WHERE MT.associatedEmotion = newWords.associatedEmotion );
逻辑验证
修正后的代码会按照你的需求执行:检查words表中是否存在与待插入行associatedEmotion匹配的记录,如果不存在任何匹配行,就将这两行数据插入到表中;如果已经存在对应associatedEmotion的记录,则不会执行插入操作。
内容的提问来源于stack exchange,提问作者Kickergold
相关产品推荐
相关产品推荐

