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

Spo*_*ook 3 sqlite unique sql-update

我有一个简单的表格:

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

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

begin transaction;
update ChecklistStep set StepIndex = 0 where id = 6;
update ChecklistStep set StepIndex = 1 where id = 5;
commit transaction;
Run Code Online (Sandbox Code Playgroud)

原因:

UNIQUE constraint failed: ChecklistStep.Checklist, ChecklistStep.StepIndex
Run Code Online (Sandbox Code Playgroud)

这样的更新怎么写?

CL.*_*CL. 6

SQLite 没有延迟 UNIQUE 约束。

PRAGMA writable_schema使坏,因为如果你更改了表而不更新索引的内部索引将被损坏,不在这里工作了。

唯一的方法是使用一个保证不被使用的临时值:

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;
Run Code Online (Sandbox Code Playgroud)

  • 为了使事情更清晰,我还将使列可以为空并使用 null 而不是任何值。感谢您的回答,我想这是唯一可行的选择。 (2认同)