snippetsqlMinor
How to use Unique key via combinations of table fields?
Viewed 0 times
uniquecombinationsfieldsviahowusetablekey
Problem
Take a look at the following sqlfiddle: http://sqlfiddle.com/#!2/dacb5/1
I have a basic table of contacts. The
I want to be able to run
So for example, if I tried to insert a contact that had
So basically,
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?Solution
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`)
);Code Snippets
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`)
);Context
StackExchange Database Administrators Q#17761, answer score: 9
Revisions (0)
No revisions yet.