logitech2004 logitech2004 - 23 days ago 8
MySQL Question

Primary key for multiple columns?

I have this MySQL Table, the PRIMARY KEY (ID).

ID | COLOR | SIZE
====================
| 1 | RED | 1 |
| 2 | RED | 2 |
| 3 | RED | 3 |
| 4 | GREEN | 1 |
| 5 | GREEN | 2 |
| 6 | BLUE | 1 |
===================


When i insert this row for example

INSERT INTO `test`(`COLOR`, `SIZE`) VALUES (RED',1);


i have a duplicate row
1, RED, 1
and
7, RED, 1
how to avoid this problem?

Thanks

Answer

You can use alter table

ALTER TABLE `test`
ADD UNIQUE (color, size)
Comments