Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two column primary key in MySQL

I have a very simple problem and a solution that will work, but I'm looking for a simpler one.

I'd like to prevent rows from being added to a database when multiple values equal existing values. For example, if a2=a1 AND b2=b1 then the data gets rejected. If only a2=a1 or only b2=b1 it is allowed. Basically I want it to act like a primary key that requires both values to match.

I know I can do this through validation before I write to the database--ex. select * where a='a2' and b='b2' and then avoid writing new data when I get results. What I'd rather do is enable a MySQL setting, like primary key, that will block data like this automatically.

I'm not very familiar with MySQL outside of basic features, so apologies if this is trivially easy. Googling for all sorts of things around unique index and primary key did not help.

like image 824
Evan Avatar asked Dec 05 '08 01:12

Evan


1 Answers

Create a unique index for the columns that you want to be unique.

Eg:

CREATE UNIQUE INDEX index_name ON table(col1, col2);

See the MySQL Create index manual.

like image 193
gcores Avatar answered Sep 24 '22 13:09

gcores