insert contacts into database but does not want to duplicate already existing contact

前端 未结 4 1614
失恋的感觉
失恋的感觉 2020-12-07 06:23

I am trying to insert contacts into database but does not want to duplicate already existing contact.

Not sure INSERT has WHERE CLAUSE.

Any ideas?

         


        
相关标签:
4条回答
  • 2020-12-07 06:46

    Perhaps you want to do an "upsert"? That means that you try to do an INSERT, and if the record already exists, you do an UPDATE instead.

    To do that, first use a SELECT to see if the record already exists. If the contact isn't in the database, do an INSERT. If the contact is already in the database, do an UPDATE.

    0 讨论(0)
  • 2020-12-07 06:53

    Another option is:

    //Insert INTO contact database
    $user_id = userid;
    $sql_insert = "INSERT into `jt_members_external_contacts`
                                (`j_user_id`,`contact_email`,`firstname`)
                   SELECT       '$user_id','$email','$name'
                    FROM        `jt_members_external_contacts`
                   WHERE        j_user_id !=$user_id AND contact_email != $email;";
    
    0 讨论(0)
  • 2020-12-07 06:56

    You could use a stored procedure that checks if the record first exists before doing an insert. If the record exists, the stored procedure would do an update.

    The advantage of using a stored procedure instead of a select followed by an update is you only hit the database server once instead of twice.

    0 讨论(0)
  • 2020-12-07 06:57

    You can use:

    INSERT ... ON DUPLICATE KEY UPDATE
    

    http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

    0 讨论(0)
提交回复
热议问题