SQLite Unique Key,包含两列组合

时间:2013-12-18 01:45:13

标签: sql database database-design sqlite

我尝试确保在运行以下查询时,只有第一个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 
);

1 个答案:

答案 0 :(得分:25)

添加到您的ddl

create table ... ( ...
...,
unique(slot, player));