5 sqlite identity unique auto-generate
我有一个要插入数据库的字符串列表.它们必须是独一无二的.当我插入我想要他们的ID(用作另一个表中的外键)所以我使用last_insert_rowid.我遇到了2个问题.
我怎么得到他们的ID?如果我不需要我不想使用select语句检查并插入字符串,如果它不存在.我该怎么办?
Noa*_*oah 10
发生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
Run Code Online (Sandbox Code Playgroud)
解决方法是更改c2列的定义,如下所示
create table b (c1 integer primary key, c2 text UNIQUE ON CONFLICT IGNORE);
Run Code Online (Sandbox Code Playgroud)
并从插入中删除"或替换"条款;
然后在插入后进行测试时,您需要执行以下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
Run Code Online (Sandbox Code Playgroud)
第3次插入后更改的返回值将是通知您的应用程序,您需要查找"test-1"的rowid,因为它已经存档.当然,如果这是一个多用户系统,您还需要将所有这些包装在一个事务中.
小智 3
我目前使用以下
insert into tbl(c_name) select 'val' where not exists(select id from tbl where c_name ='val');
select id from tbl where c_name ='val';
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15075 次 |
| 最近记录: |