插入两个相互引用的SQL表,而无需执行单独的查询

Inserting into two SQL tables that reference each other without having to execute separate queries?

本文关键字:查询 单独 执行 SQL 插入 两个 引用      更新时间:2023-10-16

所以我有两个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)

这样的事情可能吗?如果我手动定义主键是什么(而不是使用自动递增),我可以将这个手动定义的值传递给两个插入吗?

如果不使用自动增量特性,则可以自己管理主键,只需将相同的值传递给两个方法。这样做的唯一缺点是,您现在必须知道哪些主键可用于执行插入。

如果表a和表B之间是一对一的关系,那么将它们合并成一个表并一次将所有数据输入到该表中可能会更有效。

SQLite有函数sqlite3_last_insert_rowid:

sqlite3_last_insert_rowid(D)接口返回数据库连接D上最近一次成功插入到rowid表或虚拟表中的rowid。

或者,您可以使用last_insert_rowid SQL函数