MySQL两栏式唯一键

GDa*_*vid 1 mysql database key unique-key

我知道我可以使两列唯一键,但这并不是我想要的。

我想例如,如果col1='1', col2='2'那不能再有一行col1='1', col2='2',但完全有可能做到以下几点:

+--------+--------+
|  col1  |  col2  |
+--------+--------+
|    1   |    1   |
|    1   |    2   |
|    2   |    1   |
|    2   |    2   |
+--------+--------+
Run Code Online (Sandbox Code Playgroud)

虽然这是不可能的:

+--------+--------+
|  col1  |  col2  |
+--------+--------+
|    1   |    1   |
|    1   |    1   |
+--------+--------+
Run Code Online (Sandbox Code Playgroud)

同时创建两个唯一键不是一个选择,col1='1', col2='1'并且col1='1', col2='2' col1是相同的,并且如果两个都是唯一键则不允许这样做。

小智 6

您只需在两列之间声明一个唯一索引col1,并且col2

CREATE TABLE Table1
(
  `col1` int, 
  `col2` int,
   UNIQUE `unique_index`(`col1`, `col2`)
);
Run Code Online (Sandbox Code Playgroud)

如果您尝试将1, 1, 插入到 col1 和 col2 中,您将收到以下错误:

Duplicate entry '1-1' for key 'unique_index'
Run Code Online (Sandbox Code Playgroud)

您可以在这里亲自尝试一下。


Sam*_*mir 6

你需要composite unique index

ALTER TABLE tablename ADD UNIQUE KEY `uidx` (`col1`, `col2`);
Run Code Online (Sandbox Code Playgroud)