简体   繁体   English

如何将连续的ID序列恢复为SQL数据库中的主键?

[英]How to restore a continuous sequence of IDs as primary keys in a SQL database?

I'm using a SQlite database and Django's QuerySet API to access this database. 我正在使用SQlite数据库和Django的QuerySet API来访问此数据库。 I wrote data sequentially into the database and each entry has a simple ID as the primary key (this is the Django default). 我按顺序将数据写入数据库,每个条目都有一个简单的ID作为主键(这是Django的默认值)。 This means that there is a continuous sequence of IDs now in the database (entry 1 has ID 1, entry 2 has ID 2, and so on). 这意味着数据库中现在存在连续的ID序列(条目1具有ID 1,条目2具有ID 2,依此类推)。 Now I needed to delete some entries again. 现在我需要再次删除一些条目。 This means that the sequence of IDs is discontinuous now (entry 1 has ID 1, but entry 2 might have ID 3, 8, 1432 or anything else, but not 2). 这意味着ID序列现在是不连续的(条目1具有ID 1,但条目2可能具有ID 3,8,1432或其他任何东西,但不是2)。

How can I restore this continuous sequence of IDs again and associate them with the remaining entries in the database? 如何再次恢复此连续ID序列并将其与数据库中的其余条目相关联? Is there a way to do this with Django's QuerySet API or do I need to use plain SQL? 有没有办法用Django的QuerySet API做到这一点,还是我需要使用纯SQL? I have no experience with plain SQL, so some working code would be very helpful in this case. 我没有使用纯SQL的经验,因此在这种情况下,一些工作代码会非常有用。 Thank you! 谢谢!

I cannot think of any situation in which doing this would be desirable. 我无法想到任何这样做的情况。 The best primary keys are immutable (although that's not a technical requirement) and the very purpose of using non-meaningful integer primary keys is to avoid having to update them. 最好的主键是不可变的(虽然这不是一个技术要求)和使用非有意义的整数主键的根本目的是为了避免更新它们。

I would even go so far as to say that if you require a meaningful, unbroken sequence of integers, create a separate column in your table, keep the primary key with its sequence breaks, and renumber the new "sequence" column when needed. 我甚至会说,如果你需要一个有意义的,不间断的整数序列,在表中创建一个单独的列,保持主键的序列中断,并在需要时重新编号新的“序列”列。

However, you may have requirements that I can't think of. 但是,您可能有我无法想到的要求。 If you really need to change the values in those keys make sure that all the references to that column in your database are protected by FOREIGN KEY constraints and check out the ON UPDATE CASCADE option when you declare a foreign key. 如果确实 需要更改这些键中的值,请确保数据库中对该列的所有引用都受FOREIGN KEY约束的保护,并在声明外键时检出ON UPDATE CASCADE选项。 It will instruct the database to do the updating for you. 它将指示数据库为您进行更新。

But if you don't have to this, don't. 但是,如果你没有这个,没有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM