更新主键而不触发唯一键违规
我刚刚遇到这个非常简单的情况,我需要将主键向上移动某个值。假设下表:
CREATE TABLE Test (
Id INTEGER PRIMARY KEY,
Desc TEXT);
加载了以下值:
INSERT INTO Test VALUES (0,'one');
INSERT INTO Test VALUES (1,'two');
如果尝试更新主键,它当然会失败:
UPDATE Test SET Id = Id+1;
错误:列 ID 不唯一
是否有某种方法可以暂停唯一性检查,直到更新查询运行之后?
I just came to this very simple situation where I needed to shift a primary key up a certain value. Suppose the following table:
CREATE TABLE Test (
Id INTEGER PRIMARY KEY,
Desc TEXT);
Loaded with the following values:
INSERT INTO Test VALUES (0,'one');
INSERT INTO Test VALUES (1,'two');
If there's an attempt at updating the primary key, it will, of course, fail:
UPDATE Test SET Id = Id+1;
Error: column id is not unique
Is there some way to suspend unicity check until after the update query has run?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
找到一个好的枢轴点,然后围绕该枢轴移动数据。例如,如果你所有的 ID 都是正数,那么一个好的枢轴点就是 0。
当你通常会做
这个序列而不是
For 次时,你可以找到一个类似的枢轴点,但公式只是有点难。
Find a nice pivot point, and move the data around that pivot. For example, if all your IDs are positive, a good pivot is 0.
When you would normally do
Do this sequence instead
For times, you can find a similar pivot point, but the formula is just a tad harder.
在不了解根本问题的情况下(是的,您似乎是代码的受害者并在这个代码上运行!),将 ID 乘以表中的最大值应该可行。
然而,它很脏,而且实际上,数据库由于某种原因很难更改主键......
without understanding the fundamental problem (and yeah, you seem like a victim of code and run on this one!), multiplying the ID by the largest value in the table should work.
However, it's dirty, and really, databases make it hard to change primary keys for a reason...
好的。第二次尝试。试试这个:
这将通过将窗口移动得足够远来避免更新过程中任何时候出现重复的键。
OK. Second attempt. Try this:
This will avoid duplicated keys at any time in the update process by moving the window far enough.