gpt4 book ai didi

sqlite - 如何暂时打破 SQLite 中的列唯一性?

转载 作者:行者123 更新时间:2023-12-03 17:42:33 24 4
gpt4 key购买 nike

我有一个简单的表格:

CREATE TABLE ChecklistStep (
Checklist INTEGER REFERENCES Checklist (Id),
Id INTEGER PRIMARY KEY AUTOINCREMENT,
StepIndex INTEGER NOT NULL,
Name VARCHAR NOT NULL,
UNIQUE (Checklist, StepIndex));

现在我想交换两个项目的索引。这样做我暂时打破了对(Checklist,StepIndex)的唯一性。我希望,我可以在交易中做到这一点,这样在提交之后,所有的约束都将被保留,但这不起作用:

begin transaction;
update ChecklistStep set StepIndex = 0 where id = 6;
update ChecklistStep set StepIndex = 1 where id = 5;
commit transaction;

原因:

UNIQUE constraint failed: ChecklistStep.Checklist, ChecklistStep.StepIndex

如何写这样的更新?

最佳答案

SQLite 没有延迟的 UNIQUE 约束。

PRAGMA writable_schema dirty trick在这里不起作用,因为如果您在不更新索引的情况下更改表,内部索引将会损坏。

做到这一点的唯一方法是使用保证未被使用的临时值:

begin;
update ChecklistStep set StepIndex = -99999999 where id = 6;
update ChecklistStep set StepIndex = 1 where id = 5;
update ChecklistStep set StepIndex = 0 where id = 6;
commit;

关于sqlite - 如何暂时打破 SQLite 中的列唯一性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43274214/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com