Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite Unique Key with a combination of two columns

I'm trying to make sure when I run the following query only the first INSERT INTO will work.. I know I have to make slot UNIQUE

The slot could be from 0-5 INTEGER but it doesn't mean that only 6 table data rows could be accepted into that table.

For each playerHash that matches it should only allow 6 table data rows as slot is UNIQUE (cannot have duplicate of same slot column, for each playerHash column).

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

Problem of course is they all pass and cause duplicate entries

Currently I use this table 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 
);
like image 288
SSpoke Avatar asked Dec 18 '13 01:12

SSpoke


1 Answers

Add to your ddl

create table ... ( ...
...,
unique(slot, player));
like image 98
Sam Hartman Avatar answered Sep 27 '22 19:09

Sam Hartman