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
https://forums.phpfreaks.com/topic/95145-mysql-duplicate-help/
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
https://forums.phpfreaks.com/topic/95145-mysql-duplicate-help/#findComment-487385
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.