应该怎么理解 rowid 在 sqlite 中的使用

2022-07-13 22:44:21 +08:00
 youthfire
S.O 上我记得有个贴
https://stackoverflow.com/questions/35876171/sqlite-rowid-after-deleting-rows
其中有段话我印象很深
The data for rowid tables is stored as a B-Tree structure containing one entry for each table row, using the rowid value as the key. This means that retrieving or sorting records by rowid is fast. Searching for a record with a specific rowid, or for all records with rowids within a specified range is around twice as fast as a similar search made by specifying any other PRIMARY KEY or indexed value.
总结起来:rowid - 也就是 true primary key 性能优势大

在 Sqlite 官网的 rowid table 中,又是这么阐述的:If the rowid is not aliased by INTEGER PRIMARY KEY then it is not persistent and might change. In particular the VACUUM command will change rowids for tables that do not declare an INTEGER PRIMARY KEY. Therefore, applications should not normally access the rowid directly, but instead use an INTEGER PRIMARY KEY.
总结起来:不应该直接使用 rowid

自己平时在操作 sqlite select row 的时候,一直都是直接用 rowid 来选取执行的,一开始是不知道 declare primary key as alias of rowid ,后来是发现没有使用场景用到。官网让不要 direct access 的原因是 rowid 有时候会变,比如 VACUUM 。我没有理解这句,我就是需要 rowid 重新 rebuild ,才会去用 VACUUM 的啊,否则当频繁操作添加,删除动作后,不进行 rebuild ,我再用语句操作 rowid ,可能就不是我真正需要操作的行。所以我才每次在这些动作后,都会进行 VACUUM 。主要是为了逻辑不出错,同时之后读取性能好,空间小。

但有时候 VACUUM 的时间会很长,可是不操作,此 rowid(true primary key )不是彼 rowid 啊,例如删除了第 6 行,如果不 VACUUM, 我想再操作新的第 6 行,这个时候 rowid 其实是 7 ,不是 6 ,就产生了逻辑问题啊。

阐述得略混乱,请见谅!
630 次点击
所在节点    SQLite
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/866001

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX