微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

android – 在SQLite表中检索最后一条记录(再次)

我先做了几次搜索,但仍然有一个问题.

我发现最好的答案是this SO答案.总结如下:

SELECT * FROM TABLE WHERE ID =(SELECT MAX(ID)FROM TABLE);

我想知道的是,以下方法是否也能正常工作(因为我懒得改变它,我碰巧喜欢它).

SELECT * FROM TABLE ORDER BY ID DESC LIMIT 1

根据我们的SQLite Autoincrement文档,

If no ROWID is specified on the insert, or if the specified ROWID has a value of NULL, then an appropriate ROWID is created automatically. The usual algorithm is to give the newly created row a ROWID that is one larger than the largest ROWID in the table prior to the insert. If the table is initially empty, then a ROWID of 1 is used. [emphasis added]

并进一步,

The normal ROWID selection algorithm described above will generate monotonically increasing unique ROWIDs as long as you never use the maximum ROWID value and you never delete the entry in the table with the largest ROWID. If you ever delete rows or if you ever create a row with the maximum possible ROWID, then ROWIDs from previously deleted rows might be reused when creating new rows and newly created ROWIDs might not be in strictly ascending order. [emphasis added]

关于我提出的SQL语句的问题来自最后一句话.它似乎表明,如果删除任何行,无论是否使用了最大ROWID,都可以重用以前删除的ROWID.如果我们假设从不使用最大ROWID(手动或仅使用那么多记录),那么我们只需要担心删除记录.在这种情况下,第一个SQLite documnetation摘录使听起来好像你不会遇到我的查询的任何问题.

有人有确切消息么?

我喜欢我的查询,因为它只涉及一个选择(albiet,以订单为代价).我想,我可能过分关注微小的优化,不是吗?

编辑:
实际上,重新审查上面引用的SQLite页面,我认为使用AUTOINCREMENT关键字可以保证单调增加ROWID.最后一节详细讨论了它.

If a column has the type INTEGER PRIMARY KEY AUTOINCREMENT then a slightly different ROWID selection algorithm is used. 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. If the table has previously held a row with the largest possible ROWID, then new INSERTs are not allowed and any attempt to insert a new row will fail with an SQLITE_FULL error.

我现在看起来很清楚.只是填不了表(最多9223372036854775807).

对不起,我之前只修过了这部分!

解决方法:

您显示的两个查询是等效的.

至于他们是否返回最后一条记录,这取决于“最后”的含义.如果删除行,则不能依赖任一查询来返回最后插入的行.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐