Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to avoid duplicate entry into mysql database

Tags:

php

mysql

I have a table with 3 columns - id (pk), pageId (fk), name. I have a php script which dumps about 5000 records into the table, with about half being duplicates, with same pageId and name. Combination of pageId and name should be unique. What is the best way to prevent duplicates being saved to the table as I loop through the script in php?

like image 352
Michelle Avatar asked Feb 08 '10 05:02

Michelle


People also ask

How can you avoid duplicates when you insert hundreds of thousands of entries into the same MySQL table?

First step would be to set a unique key on the table: ALTER TABLE thetable ADD UNIQUE INDEX(pageid, name); Then you have to decide what you want to do when there's a duplicate.

How do I avoid insert duplicate records in node MySQL?

How it is possible ? - Check for fields that You send to API with records in user table. Make sure they're not exist. For more detailed information to client-side app I recommend to check database table for record existence before doing insert.


2 Answers

First step would be to set a unique key on the table:

ALTER TABLE thetable ADD UNIQUE INDEX(pageid, name); 

Then you have to decide what you want to do when there's a duplicate. Should you:

  1. ignore it?

    INSERT IGNORE INTO thetable (pageid, name) VALUES (1, "foo"), (1, "foo"); 
  2. Overwrite the previously entered record?

    INSERT INTO thetable (pageid, name, somefield) VALUES (1, "foo", "first") ON DUPLICATE KEY UPDATE (somefield = 'first')  INSERT INTO thetable (pageid, name, somefield) VALUES (1, "foo", "second") ON DUPLICATE KEY UPDATE (somefield = 'second') 
  3. Update some counter?

    INSERT INTO thetable (pageid, name) VALUES (1, "foo"), (1, "foo") ON DUPLICATE KEY UPDATE (pagecount = pagecount + 1) 
like image 124
nickf Avatar answered Sep 30 '22 11:09

nickf


You can also ignore the error with mysql: INSERT IGNORE INTO TABLE ... it will ignore the key error, skip over that insert and move on to the next.

like image 25
mardala Avatar answered Sep 30 '22 09:09

mardala