SQLite auto-increment non-primary key field

前端 未结 4 1229
醉话见心
醉话见心 2020-12-01 10:56

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

4条回答
  •  自闭症患者
    2020-12-01 11:21

    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')

提交回复
热议问题