Discover & Rate New Music Check out ChartVote. Promote the music you like.


MySQL Update on Duplicate entries for Inserts

Particletree has a great article on a MySQL query that updates a record in a database when trying to insert data that has a record with a duplicate key. Check out the code below.

Old Way

PHP:
  1. $sql = 'SELECT TransId FROM Sales WHERE TransId = 123';
  2. $rs = $db->query($sql);
  3. if(mysql_num_rows($rs) == 1) {
  4.     // do an SQL UPDATE
  5. }
  6. else {
  7.     // do an SQL INSERT
  8. }

New Way

SQL:
  1. INSERT INTO Sales(TransId, STATUS, Amount)
  2. VALUES(123, 'Pending', 20)
  3. ON DUPLICATE KEY UPDATE STATUS = 'Paid'

Also keep in mind that a current bug in MySQL makes this method not replication safe. I believe this has been fixed.


Leave a Reply

RSS Feed



Recommended Sites