使用SQLite从SQL插入中获取主键

Pau*_*han 3 sql sqlite

我有一个SQL表集,看起来像这样

create table foo ( 
    id int primary key asc, 
    data datatype );

create table bar ( 
    id int primary key asc, 
    fk_foo int,
    foreign key(foo_int) references foo(id));
Run Code Online (Sandbox Code Playgroud)

现在,我想插入一个记录集.

insert into table foo (data) values (stuff);
Run Code Online (Sandbox Code Playgroud)

但是等一下 - 要让Bar全部修补好,我需要来自Foo的PK.我知道这是一个已解决的问题.

解决方案是什么?

Sys*_*min 9

试试这个

SELECT last_insert_rowid() 
Run Code Online (Sandbox Code Playgroud)

  • 我知道这是一个较旧的问题/答案,但请注意,这与上面定义的create语句无法正常工作.last_insert_rowid返回指定表的最后一个rowid.但是在上面的create table语句中,id列被定义为'int primary key'.在这种情况下,id不是rowid的别名.只有当id被声明为'整数主键'时才是这种情况.这是一个(唯一的?)情况,其中sqlite需要非常特定的列声明.'int'不够好,它必须是'整数'.否则,id和rowid不是同一个colulmn. (4认同)