SQLite组合两列的唯一键

10

我想确保当运行以下查询时,只有第一个INSERT INTO会生效.. 我知道我必须将slot设为UNIQUE

slot可以是0-5的整数,但这并不意味着该表格只能接受6个数据行。

对于每个匹配的playerHash,它应仅允许6个表格数据行,因为slotUNIQUE(对于每个playerHash列,不能具有相同的slot列的重复项)。

//Below Query Should Pass
INSERT INTO Buying(itemId, amount, price, bought, slot, playerHash) VALUES (1, 1, 1, 1, 1, 1);
//Below Query Should Fail
INSERT INTO Buying(itemId, amount, price, bought, slot, playerHash) VALUES (1, 1, 1, 1, 1, 1);
//Below Query Should Pass
INSERT INTO Buying(itemId, amount, price, bought, slot, playerHash) VALUES (1, 1, 1, 1, 1, 2);
//Below Query Should Fail
INSERT INTO Buying(itemId, amount, price, bought, slot, playerHash) VALUES (1, 1, 1, 1, 1, 2);
//Below Query Should Pass
INSERT INTO Buying(itemId, amount, price, bought, slot, playerHash) VALUES (1, 1, 1, 1, 0, 2);

问题在于它们都通过并导致重复条目。

目前我使用的是这个表的DDL。

CREATE TABLE Buying ( 
    id         INTEGER PRIMARY KEY AUTOINCREMENT,
    itemId     INTEGER NOT NULL,
    amount     INTEGER NOT NULL,
    price      INTEGER NOT NULL,
    bought     INTEGER NOT NULL,
    collected  INTEGER NOT NULL
                       DEFAULT ( 0 ),
    overpaid   INTEGER NOT NULL
                       DEFAULT ( 0 ),
    slot       INTEGER NOT NULL,
    aborted    BOOLEAN NOT NULL
                       DEFAULT ( 0 ),
    playerHash INTEGER NOT NULL 
);
1个回答

26
将其添加到您的数据定义语言(DDL)中。
create table ... ( ...
...,
unique(slot, player));

现在运行得很好,第一个插入通过了,但是下一个插入给了我一个错误。 “执行查询时出错:列slot、playerHash不唯一。” - SSpoke
1
我不知道如何使用SQLiteStudio以独特的方式将它们链接起来,结果发现这与编辑列为唯一等无关...你只需要创建一个类型为Unique的表约束,然后选择每个列的复选框即可。 - SSpoke
2
@SSpoke 记得使用 [insertorthrow] 而不是 [insert]。 - Kennedy Nyaga

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接