我有一个要插入数据库的字符串列表。它们必须是独一无二的。当我插入时,我想要他们的 ID(用作另一个表中的外键)所以我使用 last_insert_rowid。我遇到了 2 个问题。
- 如果我使用替换,他们的 id (INTEGER PRIMARY KEY) 更新哪个 打破我的数据库(条目指向 不存在的 ID)
- 如果我使用 ignore,rowid 不会更新,所以我得不到正确的 ID
我如何获得他们的 ID?如果我不需要,我不想使用 select 语句来检查和插入不存在的字符串。我应该怎么做?
最佳答案
当发生 UNIQUE 约束违规时,REPLACE 算法会在插入或更新当前行之前删除导致约束违规的预先存在的行,并且命令会继续正常执行。这会导致 rowid 更改并产生以下问题
Y:> **sqlite3 test**
SQLite version 3.7.4
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> **create table b (c1 integer primary key, c2 text UNIQUE);**
sqlite> **insert or replace into b values (null,'test-1');**
sqlite> **select last_insert_rowid();**
1
sqlite> **insert or replace into b values (null,'test-2');**
sqlite> **select last_insert_rowid();**
2
sqlite> **insert or replace into b values (null,'test-1');**
sqlite> **select last_insert_rowid();**
3
sqlite> **select * from b;**
2|test-2
3|test-1
解决方法是如下更改 c2 列的定义
create table b (c1 integer primary key, c2 text UNIQUE ON CONFLICT IGNORE);
并从您的插入内容中删除“或替换”子句;
然后在插入后进行测试时,需要执行以下 sql:select last_insert_rowid(), changes();
sqlite> **create table b (c1 integer primary key, c2 text UNIQUE ON CONFLICT IGNORE);**
sqlite> **insert into b values (null,'test-1');**
sqlite> **select last_insert_rowid(), changes();**
1|1
sqlite> **insert into b values (null,'test-2');**
sqlite> **select last_insert_rowid(), changes();**
2|1
sqlite> **insert into b values (null,'test-1');**
sqlite> **select last_insert_rowid(), changes();**
2|0
第三次插入后更改的返回值将通知您的应用程序您将需要查找“test-1”的 rowid,因为它已经在文件中。当然,如果这是一个多用户系统,您还需要将所有这些都包装在一个事务中。
关于Sqlite 插入具有唯一名称,获取 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/844885/