一尘不染

具有两列组合的SQLite唯一键

sql

我试图确保当我运行以下查询时,只有第一个查询INSERT INTO可以工作。slot UNIQUE

插槽可以是0-5 INTEGER,但这并不意味着该表只能接受6个表数据行。

对于每个playerHash匹配它应该只允许6表中的数据行作为slotUNIQUE(不能有重复的相同的时隙列,对于每个playerHash列)。

//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 
);

阅读 192

收藏
2021-03-17

共1个答案

一尘不染

添加到您的DDL

create table ... ( ...
...,
unique(slot, player));
2021-03-17