更新主键而不触发唯一键违规

发布于 2024-10-24 02:09:20 字数 401 浏览 2 评论 0原文

我刚刚遇到这个非常简单的情况,我需要将主键向上移动某个值。假设下表:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

静水深流 2024-10-31 02:09:20

找到一个好的枢轴点,然后围绕该枢轴移动数据。例如,如果你所有的 ID 都是正数,那么一个好的枢轴点就是 0。

当你通常会做

UPDATE Test SET Id = Id+1;

这个序列而不是

UPDATE Test SET Id = -Id;
UPDATE Test SET Id = -Id +1;

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

UPDATE Test SET Id = Id+1;

Do this sequence instead

UPDATE Test SET Id = -Id;
UPDATE Test SET Id = -Id +1;

For times, you can find a similar pivot point, but the formula is just a tad harder.

ゃ懵逼小萝莉 2024-10-31 02:09:20

在不了解根本问题的情况下(是的,您似乎是代码的受害者并在这个代码上运行!),将 ID 乘以表中的最大值应该可行。

update test
set id = id * (select max(id) + 1 from test)

然而,它很脏,而且实际上,数据库由于某种原因很难更改主键......

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.

update test
set id = id * (select max(id) + 1 from test)

However, it's dirty, and really, databases make it hard to change primary keys for a reason...

梦过后 2024-10-31 02:09:20

好的。第二次尝试。试试这个:

  1. 获取键列的最大值。
  2. UPDATE table SET key = key + max + 1
  3. UPDATE table SET key = key - max

这将通过将窗口移动得足够远来避免更新过程中任何时候出现重复的键。

OK. Second attempt. Try this:

  1. Get the MAX of the key column.
  2. UPDATE table SET key = key + max + 1
  3. UPDATE table SET key = key - max

This will avoid duplicated keys at any time in the update process by moving the window far enough.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文