所以我有两个sqlite表(使用C ++管理),如下所示:
Table A:
primaryKey (Primary key auto increment)
b_ref (int REFERENCES TableB(primaryKey))
added_info (text)
和
Table B:
primaryKey (Primary key auto increment)
info (text)
让我们说定期我想在B中插入一些东西,然后总是在A中插入一些内容。有没有办法可以插入到表B中并让sql返回主键,这样我就可以快速插入A而不需要在表B上运行查询?
所以从基本的角度来说,我现在正在做:
Insert into A.
QUERY A to find the primary key of what I just inserted.
Insert into B (passing the results from the above query)
我想做的是:
Insert into A and retain the primary key for this insert
Insert into B (passing the primary key from the above insert)
这样的事情可能吗?如果我手动定义主键是什么(而不是使用自动增量),我可以将这个手动定义的值传递给两个插入吗?
答案 0 :(得分:2)
SQLite具有以下功能sqlite3_last_insert_rowid:
sqlite3_last_insert_rowid(D)接口将最近成功的rowid的INSERT返回到数据库连接D上的rowid表或虚拟表中。
或者,您可以使用last_insert_rowid SQL函数。
答案 1 :(得分:2)
如果您没有使用自动增量功能,那么您可以自己管理主键,只需将相同的值传递给两种方法。唯一的缺点是,您现在必须知道可用于执行插入的主键。
如果这是表A和表B之间的一对一关系,那么将它们组合到一个表中并将所有数据一次性输入到该表中可能会更有效。