V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
SQLite
youthfire
V2EX  ›  SQLite

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

  •  
  •   youthfire · 2022-07-13 22:44:21 +08:00 · 625 次点击
    这是一个创建于 654 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 ,就产生了逻辑问题啊。

    阐述得略混乱,请见谅!
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1084 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 18:25 · PVG 02:25 · LAX 11:25 · JFK 14:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.