Norman
Norman

Reputation: 6365

Insert Ignore in MySql when there's primary key that auto increments

How can I use insert ignore in Mysql when there's a column that's primary key, and that auto increments.

I have primary keys on id (primary key auto increment), and userId and elmCol are primary keys with no auto increment.

So:

id | userId | elmCol
--------------------
 1 | 1     | 1 //Allow
 2 | 1     | 2 //Allow
 3 | 1     | 3 //Allow
 4 | 1     | 1 //Not allowed if inserted again. I've put it in here just for example
 5 | 2     | 1 //Allow
 6 | 2     | 2 //Allow
 7 | 2     | 3 //Allow
 8 | 2     | 1 //Not allowed if inserted again. I've put it in here just for example

I'm using MySql and MyIsam type tables. Can I do something like this and use insert ignore?

Upvotes: 0

Views: 1270

Answers (1)

peterm
peterm

Reputation: 92785

In order for INSERT IGNORE to work in your case you need to create a UNIQUE index on (userId, elmCol).

ALTER TABLE table_name
ADD CONSTRAINT u_userId_elmCol 
    UNIQUE (userID, elmCol);

Here is SQLFiddle demo.

Upvotes: 3

Related Questions