Mysql – How to use Unique key via combinations of table fields

insertMySQLunique-constraintuniqueidentifier

Take a look at the following sqlfiddle: http://sqlfiddle.com/#!2/dacb5/1

CREATE TABLE contacts 
    (
     id int auto_increment primary key, 
     name varchar(20), 
     network_id int,
     network_contact_id int
    );

INSERT INTO contacts
(name, network_id, network_contact_id)
VALUES
('John', 4, 10),
('Alex', 4, 11),
('Bob', 4, 12),
('Jeff', 4, 45),
('Bill', 7, 11),
('Walter', 7, 45),
('Jessie', 7, 360) ;

I have a basic table of contacts. The network_id and network_contact_id fields contain id numbers that link to other tables.

I want to be able to run INSERT IGNORE queries to this table, but I want to use the combination of the network_id and network_contact_id as the unique key to match against.

So for example, if I tried to insert a contact that had network_id = 4 and network_contact_id = 12, the INSERT IGNORE query would see that entry already exists, and ignore any error that was thrown.

So basically, network_id is not unique. network_contact_id is not unique. But the combination of the two is unique. How do I set this up? Would I have to have a single other field that is the concatenated values of the two other fields? Or is there a way to setup the keys for this table so it will do what I need?

Best Answer

Did you try

CREATE TABLE contacts (
 id int auto_increment primary key, 
 name varchar(20), 
 network_id int,
 network_contact_id int, 
 UNIQUE KEY (`network_id`, `network_contact_id`)
);