简体   繁体   中英

Mysql table with both primary and unique key constraint

I have a mysql table like below,

CREATE TABLE IF NOT EXISTS `sometable` (
  `field1` varchar(36) NOT NULL,
  `field2` varchar(36) NOT NULL,
  `field3` varchar(36) NOT NULL,
  `field4` varchar(36) NOT NULL,
  PRIMARY KEY (`field1`, `field2`)
  UNIQUE KEY `field3` (`field3`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

At what context, a record to this table would be considered as a duplicate one? Assume that, I have the following record in my table.

-------------------------------------
| field1 | field2 | field3 | field4 |
|------------------------------------
|   a    |   b    |    c   |    d   |
-------------------------------------

Now if I insert (field1,field2,field3,field4) values (a, b, cc, d) , would it throw duplicate a key error? Or By considering the unique key constraint, would it allow the entry to be inserted and make the table looks like the below?

-------------------------------------
| field1 | field2 | field3 | field4 |
|------------------------------------
|   a    |   b    |    c   |    d   |
-------------------------------------
|   a    |   b    |   cc   |    d   |
-------------------------------------

It is going to through a duplicate record error if either of the unique key constraints are violated (the primary key counts as a unique key constraint). So, if either (field1, field2) OR (field3) are repeated, you'll get an error.

So, your sample data would violate the constraints and inserting the second row would generate an error, because (field1, field2) are duplicated.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM