Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

php - Best way to avoid duplicate entry into mysql database

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...