I have a query which works just like it's supposed to, however, I want to optimize it to use less queries.
The following code is from a user medals plugin I'm creating for a bulletin board system.
$types = array('numposts', 'numthreads', 'numreps');
$medals = "";
foreach($types as $type)
{
$query = $db->query("
SELECT u.*, m.*
FROM ".TABLE_PREFIX."medals_".$type." m
LEFT JOIN ".TABLE_PREFIX."medals u ON (m.".$type."_id=u.awid)
WHERE awuid='".intval($post['uid'])."' AND type='".$type."'
ORDER BY `".$type."` DESC LIMIT 1
");
while($results = $db->fetch_array($query))
{
$medals .= "<img src=\"uploads/medals/".$results['icon']."\" border=\"0\" alt=\"".$results['descrition']."\" title=\"".$results['description']."\" /> ";
}
}
For each post, it runs this query to display the user's medals. Depending on the number of posts, the query is multiplied times three. So, for example if a thread has 10 posts...10x3 is 30...that's 30 queries being executed by just this code.
What's the best way to optimize this to use less queries? Perhaps caching? I'm not too good at optimization, so I'm asking for your input here.