Jump to content

Recommended Posts

I have hundreds of record updates coming in and the way Im doing it now is slowing down the users. Not good. This table has 1.7 million entries, and I have an index on the table.

Im wondering if there is a more efficient way to perform this query and update? (MYSQL 4.1.x)

[code]<?

// CHECK TO SEE IF AN ENTRY EXISTS
$query = "SELECT COUNT(*) AS RecordTotal FROM mytable WHERE ID = $ID && Name = '$Name'";
$result = mysql_query($query) or print (mysql_error());
   while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
     extract($row);
}

if (empty($RecordTotal)) { // IF NO ENTRY EXISTS, MAKE NEW ENTRY
     $sql = "INSERT INTO mytable (ID,Name,RecordCount) Values ($ID,'$Name',1)";
}

else { // IF ENTRY EXISTS, UPDATE RECORD COUNT
     $RecordCount++;
     $sql = "UPDATE mytable SET RecordCount=$RecordCount WHERE ID = $ID && Name = '$Name'";    
}

$result = mysql_query($sql);

?>[/code]
Link to comment
https://forums.phpfreaks.com/topic/4491-how-can-i-optimize-this/
Share on other sites

BINGO! I posted this in two places, and got the answer at the other, so I'll put it here in case anyone else runs across this.

The answer is, as of MySQL 4.1 there is a way to do an insert/update in one query. Here's how:

[code]$sql = "INSERT INTO mytable (ID,Name,RecordCount) VALUES ($ID,'$Name',1) ON DUPLICATE KEY UPDATE RecordCount = RecordCount + 1";
$result = mysql_query($sql);
[/code]
Link to comment
https://forums.phpfreaks.com/topic/4491-how-can-i-optimize-this/#findComment-15687
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.