对 2 列的组合添加唯一约束

Bos*_*wow 2 mysql

我试图使 mysql 表中的两列(组合)唯一。我已经搜索了堆栈,但解决方案不起作用。所以我会用一个例子来解释

cartID   productID
10       7           -> allowed
10       8           -> allowed
11       7           -> allowed
11       7           -> not allowed, the combination of 11 7 already exists in table
Run Code Online (Sandbox Code Playgroud)

我找到的“解决方案”如下: ALTER TABLE cart ADD CONSTRAINT uq_cart UNIQUE(cartID, ProductID);

但这似乎只是对每个列单独添加了一个约束(因此,如果 10 7 已经存在,则 10 8 也会引发异常)。

Len*_*art 5

像这样的约束:

UNIQUE(cartID, productID)
Run Code Online (Sandbox Code Playgroud)

意味着 cartID 和 ProductID 的组合是唯一的,而不是各个列。然而,您的语法中的某些内容可能使 MySQL 忽略该约束。您可以尝试以下操作:

CREATE TABLE Orders
( cartID int not null
, productID int not null
, unique (cartID, productID) );

insert into Orders (cartID, productID) values (10, 7), (10,8), (11,7),(11,7);
ERROR 1062 (23000): Duplicate entry '11-7' for key 'cartID'

insert into Orders (cartID, productID) values (10, 7), (10,8), (11,7);
Query OK, 3 rows affected (0.05 sec)
Records: 3  Duplicates: 0  Warnings: 0
Run Code Online (Sandbox Code Playgroud)