techdog
techdog

Reputation: 1481

how do i insert multiple values in mysql and avoid duplicates

How would I insert multiple rows or values and avoid duplicates in the following schema.

table schema is

id,subject1,subject2,subject3

id is auto incremented.
A duplicate would be where all subject1,subject2,subject3 already exist in a record in the exact same order.

INSERT INTO "table_name" ("subject1","subject2","subject3")  
VALUES ("cats", "dogs", "hamsters")  
VALUES ("squirrels", "badgers", "minxes")  
VALUES ("moose", "deer", "ocelots") 

In the table let's say I already have a record for

id,subject1,subject2,subject3
1,"cats", "dogs", "hamsters"

so I want it to just insert

VALUES ("squirrels", "badgers", "minxes")  
VALUES ("moose", "deer", "ocelots")

I've seen answers about avoiding duplicates for single items, but not for 3.

Upvotes: 4

Views: 2314

Answers (3)

Igor
Igor

Reputation: 2659

You need to get around with the unique key on three columns.

Example of table definition

CREATE TABLE `table_name` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'PK',
  `subject1` varchar(64) NOT NULL,
  `subject2` varchar(64) NOT NULL,
  `subject3` varchar(64) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `subjects` (`subject1`,`subject1`, `subject3`)
) ENGINE=InnoDB

Upvotes: 1

Tim
Tim

Reputation: 5822

To add the constraint in now:

ALTER TABLE {tablename}
ADD CONSTRAINT {constraintname} UNIQUE (subject1, subject2, subject3)

Upvotes: 0

Dietrich Epp
Dietrich Epp

Reputation: 213278

You want to add the UNIQUE constraint to your table. If you write the UNIQUE constraint out separately, it becomes clearer how to apply it to arbitrary combinations of columns.

CREATE TABLE table_name (
    subject1 VARCHAR(30),
    subject2 VARCHAR(30),
    subject3 VARCHAR(30),
    UNIQUE (subject1, subject2, subject3)
);

Upvotes: 3

Related Questions