Jump to content

MySQL Duplicate Help


stevil

Recommended Posts

What I'm looking for is the fastest way to check if a record exisits, if it does I need to get it's ID, if not I need to create the record and then get it's ID. I guess the best way to explain it is to show you.

 

if($BookCHK = mysql_fetch_assoc(mysql_query("SELECT book_id FROM books WHERE book_title = '$BookName';"))){
$BookID = $BookCHK['book_id'];
}else{
mysql_query("INSERT INTO books(book_title) VALUES('$BookName');");
$BookID = mysql_insert_id();
}

 

The above code does work, but I think there is probably a better way to acheive this. I originally thought a " ON DUPLICATE KEY UPDATE" in myself might work, then I realised the that "book_title" isn't a key so it just doesn't work =( Surely there is something which is better than this to achieve these results.

 

The server that is running this script will be running about 300,000,000 queries a day, so if I could cut this down to just one query and lessen the checks it would be huge load off the server's back (pun intended).

 

Anyone have any ideas? Any help would be greatly appreciated!

Link to comment
Share on other sites

Just a note as to ON DUPLICATE UPDATE :-

 

mysql_query("INSERT INTO books(book_title) VALUES('$BookName') ON DUPLICATE KEY UPDATE 1=1");
$BookID = mysql_insert_id()-(mysql_affected_rows()>1?mysql_affected_rows:0);

 

This will work, but again we have an update being run which isn't needed. Again I want to speed it up as much as possible, so would rather not have the update. This does return the correct ID and more than likely faster than my previous method. But I'm looking for the fastest possible method. I'm sure it's something REALLY simple, but I've just not had to do it before so never had to worry about it.

Link to comment
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.