SQLite数据库究竟如何更新主键id?

How exactly SQLite database update primary key id?

假设我有一个 table contacts

  id        Name            Contact_No
-----------------------------------------
   1        abc                12345
   2        lmn                56784
   3        pqr                83654
   4        uvw                17637
   5        xyz                98345

如果我从数据库中删除第 3 行,删除行之后的 id 行是什么?

如果我更新第 4 行,它会得到一个新的 id 还是更新数据库后第 4 行的 ID 将保持不变?

autoincrementautoincrement not null 有什么区别?官方文档说它会降低性能并且数据库会运行缓慢。是不是一定要和integer primary key一起写?

我已经阅读了很多 Whosebug 的答案,也阅读了 SQLite Official Documentation 但我无法理解。

假设 id 是您的 INTEGER PRIMARY KEY 列的名称。

如果您更新一行,它永远不会更改其 ID,因为它仍然是同一行。 (这就是更新的重点)。

关于创建新 ID,一切都在您链接的文档中:

相关栏目:

没有自动递增

On an INSERT, if the ROWID or INTEGER PRIMARY KEY column is not explicitly given a value, then it will be filled automatically with an unused integer, usually the one more than the largest ROWID currently in use.

没有严格的规则,它可以依赖于实现。通常它将等于 select max(id)+1。在案例 6 中,但如果删除第 5 行,则可以重复使用 id 5。 (但不要依赖这个)。

使用自动递增

If a column has the type INTEGER PRIMARY KEY AUTOINCREMENT (...) the ROWID chosen for the new row is at least one larger than the largest ROWID that has ever before existed in that same table. If the table has never before contained any data, then a ROWID of 1 is used.

因此将 NOT NULL 添加到 AUTOINCREMENT 是没有意义的。

在你的例子中,下一个 id 是 6,不管你之前删除了多少行。

如果您只使用 integer primary key,那么任何插入都将使用当前最大值 ROWIDid 实际上是一个别名)加一。因此删除行 3 并插入新行将使用 6。但是,如果您要删除行 5(将最大值 ROWID 保留在 4),则新插入的行将获得 ID 5.

如果您关心 id 不被重用,那么您需要 autoincrement。这速度较慢(除非您需要,否则建议不要这样做)的原因是 有史以来最大的值 保存在内部 table 中。然后插入必须 read/update 这个内部 table 作为它们操作的一部分。如果使用 autoincrement,则删除 35 后的插入将创建一个 ID 为 6.

的行

4 的正常更新会使 ID 保持不变,除非您使用 insert or replace 有效地删除该行并插入一个新行。这样的插入将遵循与上述相同的规则。