What's the difference between this two declaration:
CREATE TABLE `t1` (`col1` INT, `col2` INT, UNIQUE(`col1`,`col2`));
or
CREATE TABLE `t2` (`col1` INT UNIQUE, `col2` INT UNIQUE);
You've used two different ways of specifying keys, but your keys are actually different.
The first requires that the combination of col1
and col2
be unique. So you couldn't have (1,2)(1,2)(1,2)
but you could have (1,2)(1,3)(2,3)
.
The second requires that each column be unique, independently; in that case, even the latter example is invalid.
Here's the first statement, with the same syntactic approach but rewritten to match the semantics of the second:
CREATE TABLE `t1` (`col1` INT, `col2` INT, UNIQUE(`col1`), UNIQUE(`col2`));
You can read more about the syntax of table schemas in the documentation .
If you write :
`CREATE TABLE `t1` (`col1` INT, `col2` INT, UNIQUE(`col1`,`col2`));`
That means you can't have the same duo of col1
+ col2
so :
col1 | col2
1 | 1
1 | 2
2 | 1
2 | 2
It's ok but :
col1 | col2
1 | 1
1 | 2
2 | 1
2 | 2
1 | 1 // NOT OK, duplicate of first row
2 | 2 // NOT OK, duplicate of row number 4
Now if you write :
CREATE TABLE `t2` (`col1` INT UNIQUE, `col2` INT UNIQUE);
That means you can't have two identical value for col1
, neither for col2
. So :
col1 | col2
1 | 1 // OK
1 | 2 // NOT OK, you already have value 1 for col1 in row 1
3 | 1 // NOT OK, you already have value 1 for col2 in row 1
4 | 3 // OK
Is it clear for you?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.