10

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?

ypercubeᵀᴹ
  • 99,450
  • 13
  • 217
  • 306
Jake Wilson
  • 2,487
  • 8
  • 22
  • 23

2 Answers2

9

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`)
);
Derek Downey
  • 23,568
  • 11
  • 79
  • 104
6

Change the table's definition by adding a UNIQUE KEY constraint on the combination of the two columns:

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

You should also check this answer by Bill Karwin on the differences between INSERT IGNORE, REPLACE and INSERT ... ON DUPLICATE KEY UPDATE

ypercubeᵀᴹ
  • 99,450
  • 13
  • 217
  • 306