Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL INSERT IGNORE not working

Here's my table with some sample data

a_id | b_id
------------
  1    225
  2    494
  3    589

When I run this query

INSERT IGNORE INTO table_name (a_id, b_id) VALUES ('4', '230') ('2', '494')

It inserts both those rows when it's supposed to ignore the second value pair (2, 494)

No indexes defined, neither of those columns are primary.

What don't I know?

like image 876
HyderA Avatar asked Jun 14 '10 06:06

HyderA


1 Answers

From the docs:

If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row still is not inserted, but no error is issued.

(my italics).

Your row is not duplicating "an existing UNIQUE index or PRIMARY KEY value" since you have no primary key nor any unique constraints.


If, as you mention in one of your comments, you want neither field to be unique but you do want the combination to be unique, you need a composite primary key across both columns (get rid of any duplicates first):

alter table MYTABLE add primary key (a_id,b_id)
like image 137
paxdiablo Avatar answered Nov 14 '22 05:11

paxdiablo