SQLite 查询插入记录如果不存在 [英] SQLite Query to Insert a record If not exists
问题描述
如果实际上未插入,我想将记录插入到 sqlite 表中.
I want to insert a record into a sqlite table if its actually not inserted.
假设它有三个字段pk、name、address
Let's say it has three fields pk, name, address
如果之前没有添加名称,我想插入带有名称的新记录.
I want to INSERT new record with name if that name not added preveously.
我们可以在单个查询中完成此操作吗?有时似乎与 SQL 查询略有不同.
Can we do with this in a single Query. Seems like its slightly different from SQL Queries sometimes.
推荐答案
是的,您可以通过一个查询来做到这一点.
Yes, you can do that with a single query.
INSERT ON CONFLICT IGNORE 应该可以帮助您:http://www.sqlite.org/lang_conflict.html
在名称上放置一个唯一键,如果名称已存在,这将在您尝试插入记录时产生冲突.
Put a unique key on the name, this will create a conflict when you try inserting a record if the name already exists.
默认是ABORT,所以如果没有IGNORE,语句会返回错误.如果您不想这样做,请使用 IGNORE.
The default is ABORT, so without the IGNORE, the statement will return an error. If you don't want that, use IGNORE.
这篇关于SQLite 查询插入记录如果不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!