SQLite 自增非主键字段

SQLite auto-increment non-primary key field(SQLite 自增非主键字段)
本文介绍了SQLite 自增非主键字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以让非主键在每次插入时自动递增?

例如,我想要一个日志,其中每个日志条目都有一个主键(供内部使用)和一个修订号(我希望自动递增的 INT 值).

作为一种解决方法,这可以通过序列来完成,但我相信 SQLite 不支持序列.

解决方案

插入时可以做select max(id)+1.

例如:

INSERT INTO Log (id, rev_no, description)VALUES ((SELECT MAX(id) + 1 FROM log), 'rev_Id', 'some description')

请注意,这将在空表上失败,因为不会有 id 为 0 的记录,但您可以添加第一个虚拟条目或将 sql 语句更改为:

INSERT INTO Log (id, rev_no, description)值 ((SELECT IFNULL(MAX(id), 0) + 1 FROM Log), 'rev_Id', 'some description')

Is it possible to have a non-primary key to be auto-incremented with every insertion?

For example, I want to have a log, where every log entry has a primary key (for internal use), and a revision number ( a INT value that I want to be auto-incremented).

As a workaround, this could be done with a sequence, yet I believe that sequences are not supported in SQLite.

解决方案

You can do select max(id)+1 when you do the insertion.

For example:

INSERT INTO Log (id, rev_no, description) VALUES ((SELECT MAX(id) + 1 FROM log), 'rev_Id', 'some description')

Note that this will fail on an empty table since there won't be a record with id is 0 but you can either add a first dummy entry or change the sql statement to this:

INSERT INTO Log (id, rev_no, description) VALUES ((SELECT IFNULL(MAX(id), 0) + 1 FROM Log), 'rev_Id', 'some description')

这篇关于SQLite 自增非主键字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)