Monday, April 16, 2012

Is there a better way to run this mysql update?

I have the following code, which firstly retrieves each unique style from a database and then searches through the products table to find the terms associated with each style and updates the stylerefs table with the styleid and the productid:



$query = "Select id,style,terms from su_styles";

if ($results = $sudb->query($query)) {

while($result = $results->fetch_array(MYSQLI_ASSOC)) {

$id=$result['id'];
$style=$result['style'];
$terms=$result['terms'];

$query= "INSERT IGNORE INTO su_stylerefs (mykey,id)
SELECT mykey,$id FROM su_pref where (match(name) against ('$terms' in Boolean Mode))
ON DUPLICATE KEY UPDATE id=$id, mykey = su_pref.mykey";

$sudb->query($query);


Is there anyway I can rewrite this query into one, rather than looping through the results of the first query? I have 10 other similar queries that need to run every day and some of the tables in the first query could have 100s of records, which mean hundreds of connections to the database, which takes a while.



Thank you in advance





No comments:

Post a Comment