0

Suppose I have a table keywords(keyid, keyword), with keyid being the primary key and keyword being varchar and unique.

How can I insert non-existing values and ignore the values that already exist in the table without getting an error?

For example I insert a, b, c, d. Then I insert c, d, e, f. It should ignore c and d, and insert e and f.

drum
  • 5,416
  • 7
  • 57
  • 91
  • 3
    Via `INSERT IGNORE INTO...` http://dev.mysql.com/doc/refman/5.5/en/insert.html or take different action via `ON DUPLICATE KEY...` – Michael Berkowski May 12 '13 at 16:05
  • 1
    possible duplicate of ["INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"](http://stackoverflow.com/questions/548541/insert-ignore-vs-insert-on-duplicate-key-update) – Michael Berkowski May 12 '13 at 16:07

2 Answers2

0

Simply use ON DUPLICATE KEY, e.g.

INSERT INTO keywords (keyid, keyword) 
     VALUES (100, 'a keyword') 
         ON DUPLICATE KEY UPDATE keyid = keyid;

This way the alternative UPDATE is executed, if keyid already exists.

Cheers!

Trinimon
  • 13,839
  • 9
  • 44
  • 60
0

You can use ON DUPLICATE KEY UPDATE function. Documentation here

Example

INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
Fabio
  • 23,183
  • 12
  • 55
  • 64