【问题标题】:python SQLite3 update row id when removing one row删除一行时python SQLite3更新行ID
【发布时间】:2016-06-13 17:55:44
【问题描述】:

我一直在构建一个 python/flask 网站,到目前为止它可以工作,但是因为我实际上需要/使用 count(id)(其中 id 是自动增量主键),我不能只删除一些随机的行。

有没有人知道删除一行时更新每个其他更高 ID 的最佳方法,有点像一个列表,所以 count() 和 id 匹配。 (第一个 ID = 1,因此无需更新即可完美匹配)。

我可以将更新函数放在一个独立的脚本中并手动运行它,如果它对于大型表来说太重了。

【问题讨论】:

  • count(id) 不受序列间隙的影响。您认为不更新较高的 ID 到底有什么问题?
  • 我的问题正是 count(id) 不受行 id 影响的事实。那样很好,因为这是我想要的,但我想知道如何更新表中所有更高 ID 的出现,所以 id 将等于计数(没有缺少 id),然后更新表序列。
  • 嗯,它们很重要
  • 我不使用外键。该数据库仅包含 2 个表,完全不同且不相关。关注的表是id(int primary notnull AI)和content(text notnull) Soo还是没有回答问题

标签: python sql sqlite


【解决方案1】:

重新创建键的顺序编号的一种方法是删除表并重新构建它。考虑下面代码中的renumber() 函数:

import sqlite3
from pprint import pprint

schema = '''
    create table S (
        id integer primary key autoincrement not null,
        content text not null)'''
def init(db):
    db.execute('drop table if exists S')
    db.execute(schema)
    db.execute('insert into S ( content ) VALUES ("one")')
    db.execute('insert into S ( content ) VALUES ("two")')
    db.execute('insert into S ( content ) VALUES ("three")')
    db.execute('insert into S ( content ) VALUES ("four")')
    db.commit()

def dump(db):
    for row in db.execute('select * from S order by ID'):
        print row
    print

def renumber(db):
    # To reorganize the primary key, create a new table
    db.execute('create temp table temp_S as select content from S order by id')
    db.execute('drop table S')
    db.execute(schema)
    db.execute('insert into S (content) '
              '  select content from temp_S order by rowid')
    db.commit()


db = sqlite3.connect(':memory:')
init(db)
dump(db)
db.execute('delete from S where id in (1,3)')
db.commit()
dump(db)
renumber(db)
dump(db)

结果:

(1, u'one')
(2, u'two')
(3, u'three')
(4, u'four')

(2, u'two')
(4, u'four')

(1, u'two')
(2, u'four')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多