具有两列组合的 SQLite 唯一键

标签 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 
);

最佳答案

添加到你的ddl中

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

关于具有两列组合的 SQLite 唯一键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20648236/

相关文章:

mysql - SQL:根据多个条件选择数据?

IOS:SQLite。快速查找记录

mysql - 删除表约束问题

sql - sql db2 统计每个id在表中出现的次数

mysql - 如何为列选择优化数据类型 [innodb specific]?

mysql - 高可用双活数据库设计

sql - 如何组合一个查询使用 MIN 函数的 sql 查询

sql - 在 SQL Server 执行之前修补过时的 SQL 查询?

mysql - CakePHP 数据库 - MyISAM、InnoDB 或 Postgresql

database-design - 序列化 ORM 关系与外键